Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake target_include_directories: Do I use PUBLIC, PRIVATE or INTERFACE?

Tags:

c++

cmake

I have a CMake-library add_library(helpers helpers.h) and I want to include the source files via target_include_directories. Then I have to choose between the parameters PRIVATE, PUBLIC and INTERFACE.

What is the difference?

like image 541
Chris Avatar asked Jan 25 '26 23:01

Chris


1 Answers

  1. PRIVATE: The includes can only be used by the helpers-library itself.
  2. PUBLIC: The includes can be used by the helpers-library itself and any target that uses the helpers-library, e.g. via target_link_libraries(MainApplication PUBLIC libhelpers).
  3. INTERFACE: The includes can't be used by the helpers-library, only by targets that use the helpers-library.

This example illustrates the possible imports. Structure:

│   CMakeLists.txt
│   helper.cpp
│   main.cpp
│
├───details_interface
│       details_interface.cpp
│
├───details_private
│       details_private.cpp
│
└───details_public
        details_public.cpp

CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)
set(CMAKE_CXX_STANDARD 17)
project(cmake_experiment)

add_executable(cmake_experiment main.cpp)

target_link_libraries(cmake_experiment libhelper)

add_library(libhelper helper.cpp)

target_include_directories(libhelper
        INTERFACE details_interface
        PUBLIC details_public
        PRIVATE details_private)

main.cpp:

#include <iostream>

#include "details_public.cpp"
#include "details_interface.cpp"

// fatal error: details_private.cpp: No such file or directory:
// #include "details_private.cpp"

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

helper.cpp:

#include "details_public.cpp"
#include "details_private.cpp"

// fatal error: details_interface.cpp: No such file or directory:
// #include "details_interface.cpp"

like image 104
Chris Avatar answered Jan 27 '26 18:01

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!