1

I want to add to my CMake project some subfolder which contains some additional functionality. MyProject is a shared library. Ideally it will be fine to just include files from subfolder and to compile all them together. But so far I've found a way only to include that as a static library that suits me too. So my files structure should look like the following:

MyProject
    src
        main.cpp
    include
        main.h
    CMakeLists.txt
    3dparty
        SomeFolder
           src
               file.cpp
           include
               file.h
           CMakeLists.txt

MyProject/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)
project(MyProject)
file(GLOB SRC . src/*.cpp)
file(GLOB INC . include/*.h)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin)
add_library(${PROJECT_NAME} SHARED ${SRC} ${INC})
target_include_directories(${PROJECT_NAME} PUBLIC
  ${CMAKE_CURRENT_SOURCE_DIR}/include
)
add_subdirectory(3dparty/SomeFolder)

and 3dparty/SomeFolder/CMakeLists.txt:

project (SomeFolder)
file(GLOB SRC . src/*.cpp)
file(GLOB INC . include/*.h)
add_library(${PROJECT_NAME} STATIC ${SRC} ${INC})
target_include_directories(${PROJECT_NAME} PUBLIC
  ${CMAKE_CURRENT_SOURCE_DIR}/include
)

I can compile the project and I see that compiler produses SomeFolder.a so it looks good. But for some reason I can't include files from 3dparty/SomeFolder/include in main.*. So far I've tried:

#include "file.h"
#include "3dparty/SomeFolder/file.h"

but nothing works. I get error: 'file.h' file not found.

What I did wrong? How can I include files from subproject?

1 Answer 1

1

Because you forgot to link the sublibrary to your main library. Usr target_link_libraries()

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I've added target_link_libraries(${PROJECT_NAME} SomeFolder) to the main CMakeLists.txt and looks that that works. Is that possible to add somehow this line inside 3dparty/SomeFolder/CMakeLists.txt ? It would be nice to add subfolder with only one instruction only (add_subdirectory).
No, and I believe you're making a few wrong assumptions here. add_subirectory() will do nothing for linking (as you experienced), and the arguments of target_link_libraries() are targets (executable or library), not directory paths. The normal way to link is just to specify the dependencies for each target with target_link_libraries(). If CMake can at some point uniquely identify one of the dependencies as another target, it will know what to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.