BAK
BAK

Reputation: 1005

configure include directories for each executable with cmake

I've started a project with cmake, composed by two executables. A lot of code is used by the two executables.

Now, i need to configure differents include directories, for each executable. if i use include_directories, it add my directories for all executables.

it is possible to configure include directories independently for executable ?

This is my directories:

.
├── CMakeCache.txt
├── CMakeFiles
│   [...]
├── cmake_install.cmake
├── CMakeLists.txt
├── includes
│   ├── client
│   │   └── main.hpp
│   ├── server
│   │   └── main.hpp
│   └── shared
├── Makefile
└── sources
    ├── client
    │   ├── main.cpp
    ├── shared
    │   ├── lib.cpp
    └── server
        └── main.cpp

Upvotes: 1

Views: 1963

Answers (2)

Lincoln
Lincoln

Reputation: 1108

It really depends on your project and directory layout as to whether add_subdirectory makes sense. It is good at splitting up parts of a project that are separable and with your simple example that strategy is reasonable.

Another way to handle this is to use target_include_directories to specify per target includes. This is really useful when you are making several targets from the same folder, so everything would need to be specified in one CMakeLists.txt, however it works fine in your case as well. For your example your CMakeLists.txt would look something like the following:

project(client_server)

# global include directories shared by library, server, and client
include_directories(
  includes
  includes/shared)

# Make the shared library
add_library(client_server_lib sources/lib.cpp)

# Make the server (using its own server directory)
add_executable(server sources/server/main.cpp)
target_include_directories(server PUBLIC
  includes/server # add the server's specific include file
)
target_link_libraries(server client_server_lib) # link the server with the shared library

# make the client
add_executable(client sources/client/main.cpp)
target_include_directories(client PUBLIC
  includes/client # add the client's specific include file
)
target_link_libraries(client client_server_lib) # link client with the shared library

Additional info at https://cmake.org/cmake/help/v3.0/command/target_include_directories.html

Upvotes: 2

arrowd
arrowd

Reputation: 34401

You should create CMakeLists.txt for both of your executables in their dirs (sources\client\CMakeLists.txt and sources\server\CMakeLists.txt). There you can include_directories() and this would not interfere with other targets.

Do not forget to do add_subdirectory() in your root CMakeLists.txt.

Upvotes: 5

Related Questions