Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: set directory for target sources

Tags:

c++

cmake

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.

like image 506
Chris K Avatar asked Apr 03 '19 11:04

Chris K


People also ask

What are target directories?

Specifies include directories to use when compiling a given target. The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target. By using AFTER or BEFORE explicitly, you can select between appending and prepending, independent of the default.

How do you set a variable in CMakeLists txt?

You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake .

How add include path CMake?

First, you use include_directories() to tell CMake to add the directory as -I to the compilation command line. Second, you list the headers in your add_executable() or add_library() call.


1 Answers

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/")
like image 136
KamilCuk Avatar answered Nov 14 '22 22:11

KamilCuk