Search code examples
c++cmakestatic-librariesinclude-path

Change include path of static library


I want to make a static library from a project of mine such that I can use it like this in other projects:

#include <MonoEngine/engine.hpp>

However right now I have a src folder in between:

#include <MonoEngine/src/engine.hpp>

How can I build the static library with CMake such that I can omit the src/?

This is roughly how my library folder is structured.

monoEngine
|-src
| |-engine.hpp
| |-engine.cpp
| |-subfolder1
|   |-file.hpp
|   |-file.cpp
|-CMakeLists.txt

Solution

  • Create subfolder include and place all your headers in there and add that folder to your include path:

    monoEngine
    |-include
    | |-MonoEngine
    | | |-engine.hpp 
    | | |-subfolder1
    | |   |-public.hpp
    |-src
    | |-engine.cpp
    | |-subfolder1
    |   |-private.hpp (will not be shared with third parties)
    |   |-file.cpp
    |-CMakeLists.txt
    

    That way headers in the include will provide the public interface of your library, while headers in the src-directory will not be exposed to third parties using your library. That's the common approach if build a library.

    Addendum:

    Since you asked in the comments below how to use this with CMake, a simple CMakeLists.txt could look like this (untested):

    project( your_project )
    cmake_minimum_required( VERSION 3.0 )
    
    set( SRC_LIST 
        include/MonoEngine/engine.hpp
        include/MonoEngine/subfolder1/public.hpp
        src/engine.cpp
        src/subfolder1/file.cpp
        src/subfolder1/private.h )
    
    add_library( your_lib ${SRC_LIST} )
    target_include_directories( your_lib PUBLIC ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/src )
    
    # and then optional parameters:
    # target_compile_options( your_lib ... )
    # target_link_libraries( your_lib ... )
    # install(TARGETS your_lib ... )