cmake object 使用外部附加 header 文件构建库

cmake object library build with external aditional header file

我想在 cmake object 库 mylib 中构建一个测试可执行文件。这只是一个简单的测试设置。该库包括一个 src a.c 和一个 header a.h。问题是 cmake object lib 还需要额外的 header 用于配置 a_config.h。我没有找到使用附加 header 和 object 库构建可执行文件的解决方案。 所以我把这个例子推到了github:https://github.com/mgiaco/mylib/blob/master/verify/CMakeLists.txt

文件夹结构:

 mylib
     build
     include
       a.h
     src
       a.c
     verify
       source
         a_config.h
         mylib_test.c
         CMakeList.txt   // one
     CMakeList.txt       // two

CMakeList.txt(一)

list (APPEND verify_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/source)
message("mylib")
list (APPEND verify_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/source/mylib_test.c)

add_executable(verify_exe ${verify_SOURCE} ${verify_HEADER})
target_include_directories(verify_exe PUBLIC ${verify_HEADER})
target_link_libraries(verify_exe $<TARGET_OBJECTS:mylib_obj>)

CMakeList.txt(二)

cmake_minimum_required(VERSION 3.13)
message("verify")
project(mylib VERSION 1.0.0)

add_library(${PROJECT_NAME}_obj OBJECT ${CMAKE_CURRENT_SOURCE_DIR}/src/a.c)

target_include_directories(${PROJECT_NAME}_obj
    PUBLIC 
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
    
add_subdirectory(verify)

运行 和错误

C:\workdir\io\mylib\build (master)
λ cmake.exe -DCMAKE_SH="CMAKE_SH-NOTFOUND" -G"MinGW Makefiles" ..
verify
mylib
-- Configuring done
-- Generating done
-- Build files have been written to: C:/workdir/io/mylib/build

C:\workdir\io\mylib\build (master)
λ mingw32-make.exe
[ 33%] Building C object CMakeFiles/mylib_obj.dir/src/a.c.obj
C:\workdir\io\mylib\src\a.c:10:10: fatal error: a_config.h: No such file or directory
 #include "a_config.h"
          ^~~~~~~~~~~~
compilation terminated.
mingw32-make[2]: *** [CMakeFiles\mylib_obj.dir\build.make:63: CMakeFiles/mylib_obj.dir/src/a.c.obj] Error 1
mingw32-make[1]: *** [CMakeFiles\Makefile2:95: CMakeFiles/mylib_obj.dir/all] Error 2
mingw32-make: *** [Makefile:83: all] Error 2

我做错了什么?

谢谢 马蒂亚斯

您不想构建源代码,那么创建库不是解决方案 - 库是 已编译 源代码的集合。通常我做一个功能,让用户可以轻松添加库:

# mylib/CMakeList.txt

# 'a' as in the library named 'a', not as an article but as a name
set(_add_a_library_source_dir ${CMAKE_CURRENT_LIST_DIR})
function(add_a_library name)
   add_library(${name} ${ARGN} ${_add_a_library_source_dir}/src/a.c)
   taget_include_directories(${name}
       PUBLIC 
           $<BUILD_INTERFACE:${_add_a_library_source_dir}/include>
    )
endfunction()

然后图书馆的用户可以这样做:

# mylib/verify/CMakeLists.txt

add_a_library(verify_a_library OBJECT)
# add path to a_config.h to a library
target_include_directories(verify_a_library ${CMAKE_CURRENT_SOURCE_DIR})

add_executable(verify_exe ${sources})
target_link_libraries(verify_exe verify_a_library)

即使他们需要多个版本。

注意:如果你有足够新的cmake,就不需要$<TARGET_OBJECTS,只需要link对象库即可。