Search code examples
c++cmakecompiler-flagsheader-only

CMake: add compile flag for header only library


Unsure about how to use CMake properly here. I have one library, which is a template header only library which uses C++20 features. Therefore, I want to make sure that any [downstream/consumer/dependent] of my library compiles the specialization of my library with the correct flags.

First lib does the following:

add_library(foo INTERFACE include/foo.h)

Now, foo uses the filesystem stuff from c++20, so I want to do something like this:

target_compile_features(foo INTERFACE cxx_std_20)
target_link_libraries(foo INTERFACE stdc++fs)

In my dependent, I then want to do

add_executable(bar src/bar.cpp)
find_package(foo REQUIRED)
target_link_libraries(bar foo)
// src/bar.cpp
#include "foo.h" // or something like that

Currently, linker fails. What's the proper way to set this up?


Solution

  • target_link_libraries is to set libraries to link with when actually building the specified target. The problem here is that INTERFACE libraries aren't built.

    You need to add the libraries to link with as a dependency for your library.

    This is done with the set_target_properties command to set the INTERFACE_LINK_LIBRARIES property:

    set_target_properties(foo
        PROPERTIES INTERFACE_LINK_LIBRARIES stdc++fs)