CMake: set directory for target sources

2019-08-02 04:25发布

问题:

I have a C++ project where all implementation source files (*.cpp) reside in a src directory within the project directory. Some of the files are in further subdirectories. Let's say there are 50 files in src/foo/. I need to list these files as part of the add_library and/or the target_sources function.

Now, everywhere one looks, adding all files from a directory automtically is discouraged, which is fine with me. So I am going to list all the files manually; but repeating the common prefix src/foo/ 50 times seems really silly and is annoying.

In the documentation for target_sources it says

Relative source file paths are interpreted as being relative to the current source directory (i.e. CMAKE_CURRENT_SOURCE_DIR).

So I've added set(CMAKE_CURRENT_SOURCE_DIR "src/foo/") before the call to target_source but it didn't work. (I get a "Cannot find source file" error.)

So what is the correct way to achieve what I want if it is even possible?

N.B.: The (public) header files (*.hpp) of the project are in an include directory (outside of src). This is nicely configured (without having to list the individual files) with the target_include_directories function.

回答1:

but repeating the common prefix src/foo/ 50 times

Just prepend the prefix to the sources.

set(target_sources
    source1.c
    source2.c
)
list(TRANSFORM target_sources PREPEND "src/foo/")


回答2:

Setting CMAKE_CURRENT_SOURCE_DIR as a relative variable to the old CMAKE_CURRENT_SOURCE_DIR is not going to work. If it's set to a value, then it's fair to assume that removing that value and using a custom one will be wrong because you are missing what it was set to before.

You might want to set it as an absolute path, or use set(CMAKE_CURRENT_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/foo/"), or do as lots of other people and copy paste the prefix all the time. That's the standard practice (which is also one of the reason I still use GLOB, because I'm lazy), following up on explicit is better than implicit (which is the point of not using GLOB).



标签: c++ cmake