Better CMakeLists.txt for own Classes headers and cpp files

Better CMakeLists.txt for own Classes headers and cpp files

Just as ndk-build while build android project, when we use Cmake for Android build, we don’t need to add every new file (.h or .cpp) in Classes dir manually, we can auto add all the headers and cpp files in a better way.

below is my code in CMakeLists.txt
FILE(GLOB_RECURSE USER_HEADER “Classes/.hpp" "Classes/.h”)

MESSAGE("打印Classes 目录下所有的头文件 ---")

MESSAGE("打印Classes 目录下所有的cpp文件 ---")

# add cross-platforms source files and header files

Be very careful when and where you use GLOB and GLOB_RECURSE. There is a lot of information online about why you should avoid it, or at the very least use it selectively (such as in sub-folders with their own CMakeLists.txt).

More info here and here.

1 Like

Ok, i am not good at CMakeList, i add those code, because i want to auto add my own cpp files while build Android with CMake.
Do you have any good ideas on it ?

How CMake works and how best to utilize it is a topic that is covered all over the internet, so do a few net searches and I’m sure you’ll learn a lot about it.

As for how best to add source files, the common way is to add references to each individual source file explicitly, and not use things like GLOB. I don’t quite understand why it’s an issue, given it takes a few seconds to type up a new entry in the CMakeLists.txt.

1 Like

It’s because i am port an old project from ndk to cmake, so i have many user cpp files need to be added to CMakeList.txt.

For new project or new file, yes, it’s very easy to add one file to the txt file one time. and just take a few minutes.

Easy to fix. Dump the directory contents to a text file, then copy it as a block and add it to your CMakeLists.txt. For example, this is one way to do it:

dir *.h *.cpp > filelist.txt

Use an editor that lets you select in column mode (like Notepad++ or Visual Studio), and just copy the files without the extra info and paste into your CMakeLists.txt. Saves you having to type them out manually.

In my projects I decided to use glob. I know that this is bad… But that works for me.

There is option CONFIGURE_DEPENDS to make glob better:


This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.