Search code examples
c++command-linecmakeg++include-path

CMake: How to choose which include directories get passed for each source file


I have a project with many source files, and header files. I could add every single directory that contains a header file to CMake's include directories so they are passed via -I option to the compiling of each source file.

include_directories(I/will/need/tons/of/these);

Is there any way through CMake that I can pass only the relevant include directories to the compiling of each source file?

For example, If i was writing this myself on the command line, I would use a script like this:

g++ -I $(./get_include_dirs.sh foo.cpp) -o foo.o foo.cpp

where $(./get_include_dirs.sh foo.cpp) is a script that gets expanded to only the include dirs of foo.cpp

Can this be done on CMake? I don't know how to tell cmake to use that script for each file


Solution

  • Normally, you should set include directories not globally but on target level:

    set(my-target-sources
      source1.cpp
      ...
      sourceN.cpp
    )
    add_library(my-target
      ${my-target-sources}
    )
    target_include_directories(my-target
      [PUBLIC|PRIVATE|INTERFACE]
        directory-relevant-to-my-target
    )
    

    This way, the compiler will look for header files in directory-relevant-to-my-target when compiling my-target. I think that there is no reason for setting the include directories on source file granularity.

    For executing a script from CMake you can use execute_process and collect your list of directories in the OUTPUT_VARIABLE parameter but I would not propose that since you will lose inherent portability of CMake when doing so.