Is there a way in CMake to use a library for multiple targets with different static dependencies? To explain it better, consider this minimal example: I want two executables: The first should print "YES", the second one should print "NO". For this I use the libarary "printsth", which prints "something". The string it prints comes from the header file the "user" (either printyes or printno) supplies. This altogether looks like this:
├── apps
│ ├── printno
│ │ ├── CMakeLists.txt
│ │ │ add_executable(printno main.cpp)
│ │ │ target_link_libraries(printno PRIVATE printsth)
│ │ │
│ │ ├── main.cpp
│ │ │ #include "printsth/printsth.h"
│ │ │
│ │ │ int main() {
│ │ │ printsth();
│ │ │ return 0;
│ │ │ }
│ │ │
│ │ └── print_usr.h
│ │ #define USR_STRING "NO"
│ │
│ └── printyes
│ │ ├── CMakeLists.txt
│ │ │ add_executable(printyes main.cpp)
│ │ │ target_link_libraries(printyes PRIVATE printsth)
│ │ │
│ │ ├── main.cpp
│ │ │ #include "printsth/printsth.h"
│ │ │
│ │ │ int main() {
│ │ │ printsth();
│ │ │ return 0;
│ │ │ }
│ │ │
│ │ └── print_usr.h
│ │ #define USR_STRING "YES"
│ │
├── extern
│ └── printsh
│ ├── include
│ │ └── printsh
│ │ └── printsh.h
│ │ void printsth();
│ │
│ ├── src
│ │ ├── CMakeLists.txt
│ │ │ add_library(printsth printsth.cpp)
│ │ │ target_include_directories(printsth PUBLIC ../include)
│ │ │
│ │ └── printsh.cpp
│ │ #include "printsth/printsth.h"
│ │ #include "print_usr.h"
│ │ #include <iostream>
│ │
│ │ void printsth() {
│ │ std::cout << USR_STRING << std::endl;
│ │ }
│ │
│ └── CMakeLists.txt
│ cmake_minimum_required(VERSION 3.11...3.16)
│
│ project(printsh
│ VERSION 0.1
│ DESCRIPTION "Print something"
│ LANGUAGES CXX)
│
│ add_subdirectory(src)
│
└── CMakeLists.txt
cmake_minimum_required(VERSION 3.11...3.16)
project(printexamples
VERSION 0.1
DESCRIPTION "Print examples"
LANGUAGES CXX)
add_subdirectory(apps/printyes)
add_subdirectory(apps/printno)
add_subdirectory(extern/printsth)
When building I obviously get the error
fatal error: print_usr.h: No such file or directory
So is there any change I can tell CMake to use apps/printno as include directory when building printsh lib for printno and to use apps/printyes as include directory when building for printyes?
I know this example does not make much sense and it is easy to get rid of the header dependencies (e.g. passing the custom string as an argument to printsth()) and everything works just fine. So this is just an example to demonstrate a "real-world" problem, where I can't easily get rid of the dependencies.