最近在使用android studio的時候又發現了一個非常不方便的地方:
每次創建新的C++文件,都需要手動把新創建的C++文件名添加到CMakeLists.txt文件中,不然的話編輯器的頂部就會一直報:

目前我的項目結構如下:

對應的CMakeLists.txt文件如下:
# For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.4.1) # Add header file path # include_directories(src/main/cpp/include) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. add_library( # Sets the name of the library. HaAlgorithm # Sets the library as a shared library. SHARED src/main/cpp/HaAptUserTuneJNI.cpp src/main/cpp/AndroidLog.cpp # Algorithm src/main/cpp/HaAlgorithm/apt_tune.cpp src/main/cpp/HaAlgorithm/invfreqz.cpp src/main/cpp/HaAlgorithm/main.cpp src/main/cpp/HaAlgorithm/sort_sos.cpp src/main/cpp/HaAlgorithm/tf2sos.cpp src/main/cpp/HaAlgorithm/user_tune_eq.cpp src/main/cpp/HaAlgorithm/wdrc_payload.cpp # CommandDefine src/main/cpp/HaCommandDefine/NoiseReductionPayload.cpp ) # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. target_link_libraries( # Specifies the target library. HaAlgorithm android # Links the target library to the log library # included in the NDK. ${log-lib})
可以看到,add_library 一行中已經添加了很多的cpp 文件, 有些還在第二級的子目錄。
解決辦法:
可以通過file指令搜索出所有后綴名為".cpp"的文件,然后添加到項目中,新的CMakeLists.txt修改如下:
cmake_minimum_required(VERSION 3.4.1) set(CMAKE_CXX_STANDARD 11)
file(GLOB_RECURSE native_srcs src/main/cpp/*.cpp) add_library(HaAlgorithm SHARED ${native_srcs}) target_link_libraries( HaAlgorithm android log )
重點在於標紅的那一句,什么意思呢,相當於告訴CMake, 搜索當前目錄以及子目錄中所有的以.cpp結尾的文件,然后把它們保存到 native_srcs 變量中。這里要注意CMakeLists.txt文件的位置,我是放在項目根目錄下,所以我在搜索的時候指定了前綴:src/main/cpp。
這樣修改之后,以后再添加新的C++代碼就不需要再修改CMake文件了,編譯APK的時候CMake會自動找出符合條件的C++文件並且參與到構建當中。
美中不足的是,雖然編譯最終apk的時候,新添加的文件也會被編譯,但是新添加的C++文件上方還是會出現:

並且點擊右邊的“Sync Now” 之后還是沒用!
經過反復嘗試發現可以通過點擊菜單欄上的“Refresh Linked C++ Projects” 讓它消失。
