Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - CMake: set directory for target sources

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...