Header files with a prefix in the CMake project

I created a CMake project whose directory structure is as follows:

src/ --CMakeLists.txt --libA/ ----CMakeLists.txt ----foo.h ----foo.cpp --main/ ----CMakeLists.txt ----main.cpp 

src/CMakeLists.txt uses add_subdirectory to draw in libA and main . libA/CMakeLists.txt uses add_library to define a library called libA that exports foo.h via target_include_directories . If I now contact libA in main using target_link_library , I can enable foo.h through #include <foo.h> in main.cpp .

Question: Is it possible to provide the open libA interface libA prefix so that I can (and should) write #include <libA/foo.h> in main.cpp instead?

+9
source share
2 answers

This is an old question, but I had exactly the same problem. I ended up getting around this by adding the export_headers() function that creates symbolic links to the headers in binary export_headers() :

 function(export_headers TARGET HEADER_SOURCE_DIR HEADER_DEST_DIR) # Put all headers that are in the source directory into EXPORT_HEADERS variable file(GLOB_RECURSE EXPORT_HEADERS CONFIGURE_DEPENDS RELATIVE "${HEADER_SOURCE_DIR}" "${HEADER_SOURCE_DIR}/*.h" ) # For each header that will be exported foreach(HEADER ${EXPORT_HEADERS}) # Get the directory portion that needs to be created get_filename_component(HEADER_DIRECTORY "${HEADER}" DIRECTORY) # Create the directory add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "${HEADER_DEST_DIR}/${HEADER_DIRECTORY}" ) if (MSVC) # Make a hard link to the file add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND if not exist "${HEADER_DEST_DIR}/${HEADER}" \( mklink /h "${HEADER_DEST_DIR}/${HEADER}" "${HEADER_SOURCE_DIR}/${HEADER}" \) ) else() # Make a symbolic link to the file add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ln -sf "${HEADER_SOURCE_DIR}/${HEADER}" "${HEADER_DEST_DIR}/${HEADER}" ) endif() endforeach(HEADER) endfunction() 

You would call it something like:

 add_library(libA STATIC ${LIBA_SOURCES} export_headers(libA ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/include/libA) target_include_directories(libA INTERFACE ${CMAKE_CURRENT_BINARY_DIR}/include) 

Then, if you follow the link to libA , you can #include <libA/foo.h> .

0
source

You can use the base source directory (or another directory that is the parent of libA ) in the target_include_directories() call. This allows you to define the target property INTERFACE_INCLUDE_DIRECTORIES relative to another directory (in this example, CMAKE_SOURCE_DIR ). So it will look something like this:

In libA/CMakeLists.txt :

 add_library(libA foo.cpp) # Define the include files with respect to the directory above this. target_include_directories(libA PUBLIC ${CMAKE_SOURCE_DIR}) 

File main/main.cpp :

 #include <iostream> #include <libA/foo.h> int main() { FooClass fooclass; fooclass.myFunction(); std::cout << "Hello World!" << std::endl; return 0; } 
0
source

All Articles