Search code examples
cmakecross-platform

How to include specific header with Cmake Interface Libraries?


Here is the link to the repo with code: https://github.com/BrilStrawhat/cmake-interface_lib_question

I found an interface library in the CMake documentation: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#interface-libraries

But they just don't work as I expect. I'm not able to specify and include header files, but only include the whole directory with it.

Thanks in advance.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.27)
project(interface_lib_test)

add_library(interface_lib_test INTERFACE)

# ref: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#interface-libraries
target_sources(interface_lib_test INTERFACE
  FILE_SET HEADERS # useless line
  BASE_DIRS inc # same as target_include_directories
  FILES inc/prod.h # useless line
)

add_library(platform2 INTERFACE)

target_sources(platform2 PUBLIC
  FILE_SET HEADERS
  BASE_DIRS platform2
  FILES platform2/platform.h
)

add_executable(exe1 src/main.c)
target_link_libraries(exe1 platform2 interface_lib_test)

src/main.c:

#include <stdio.h>
#include <prod.h>

int main(void) {
    printf("%d\n", PLAT);
    return 0;
}

inc/prod.h:

#include "platform.h"

int prod(void);

inc/platform.h:

#define PLAT 1

platform2/platform.h:

#define PLAT 2

Now if run cmake it builds a program and it include platform.h located in inc/ but not in platform2/. How to force cmake include platform.h from platform2/ only by changing CMakeLists.txt file?

expected:

./exe1
2

actual:

./exe1
1

Solution

  • With double quotes, the directive #include "platform.h" firstly searches the header in the current directory, and only then searches it in include directories. You probably wanted to use <>. Many thanks for the answer to https://stackoverflow.com/users/3440745/tsyvarev

    Need to use

    #include <platform.h>
    

    instead of

    #include "platform.h"