0

I'm trying to use CMake for the first time for a project and need some help setting up a project the way I like it. I'm probably doing everything wrong, so please bear with me. I currently have the following directory structure:

/CMakeLists.txt
/main/CMakeLists.txt
      main.cc
/libfoo/CMakeLists.txt
        libfoo.h
        libfoo.cc

Here libfoo is a git submodule that should be includable in other projects as well. My CMakeLists.txt files are as follows:

/CMakeLists.txt:

cmake_minimum_required (VERSION 3.10)
project(server)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
add_subdirectory(main)
add_subdirectory(libfoo)

/main/CMakeLists.txt:

set(MAIN_SRCS
    "main.cc"
) 
add_executable(server
    ${MAIN_SRCS}
)
target_link_libraries(server
    libfoo
)

/libfoo/CMakeLists.txt:

cmake_minimum_required (VERSION 3.10)
project(libfoo)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(LIBFOO_SRCS
    "libfoo.cc"
    "libfoo.h"
)
add_library(libfoo STATIC
    ${LIBFOO_SRCS}
)

My current main.cc is extremely simple:

#include "libfoo.h"

int main(int argc, char** argv) {
  return 0;
}

However, this doesn't currently compile as the libfoo.h header isn't found. My questions are therefore:

  1. Why isn't the libfoo.h header visible, since I've added the library as a target_link_library for the executable?

  2. Is there a better way to set up the CMakeLists.txt files?

  3. I would prefer to have the required include directory for the libfoo.h library to be of the form #include "libfoo/libfoo.h", so I can avoid file name collisions in the future. How can this be done?

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
del
  • 1,127
  • 10
  • 16

1 Answers1

0

By having variable CMAKE_INCLUDE_CURRENT_DIR set, you automatically include directory libfoo/ (for search header files) when file libfoo/CMakeLists.txt is processed.

However, like with include_directories command, this doesn't affect on the parent directory: libfoo/ isn't included when CMakeLists.txt is processed. See, e.g., that question: No such file or directory using cmake.

You may set variable CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE, so libfoo/ will be "attached" as include directory to any target created in libfoo/CMakeLists.txt. Thus, linking with such target (libfoo in your case) will propagate include directory.

CMakeLists.txt:

# This will include current directory when building a target
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# This will *attach* current directory as include directory to the target
set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)

(Note, that it is sufficient to set the variables only in top-level CMakeLists.txt: all variables are automatically propagated to subdirectories.)


I would prefer to have the required include directory for the libfoo.h library to be of the form #include "libfoo/libfoo.h"

So you need to have a file <some-dir>/libfoo/libfoo.h and include <some-dir>.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153