我们想要组织一个C++
项目,如下所示:
project/
lib1/ (first library)
CMakeList.txt
src/
lib1.c
foo1.h
build/
test/ (tests)
CMakeList.txt
test1.c
test2.c
lib2/ (second library)
CMakeList.txt
src/
CMakeList.txt
os/ (OS dependent code)
CMakeList.txt
win32/
xxx.c (win32 implementation)
linux/
xxx.c (linux implementation)
lib2.c
foo2.h
build/
include/ (shared/public headers)
lib1/
lib.h (shared library header included from apps)
lib2/
lib.h (shared library header -"-)
请问当
CMakeLists.txt
应该使用lib2
时以及例如link1
应该是可移植的(至少是Win32,Linux ...)?更正:如果某些
lib2
文件不在其位置,请假定是。我可能忘了 最佳答案
整个理念是从整个项目的中央CMakeLists.txt开始。在这个级别上,所有目标(库,可执行文件)都将被聚合,因此从lib1到lib2的链接不会有问题。如果lib2要链接到lib1,则需要先构建lib1。
特定于平台的源文件应有条件地设置为某个变量。
(如果需要在子目录中设置变量并在上面的目录中使用它,则必须使用CACHE FORCE等将其设置为缓存-请参见set
手册)
这是您正确地进行源代码构建的方式-如CMake所愿:
cd project-build
cmake ../project
每个库有单独的构建目录不是很CMake'ish(如果我可以这么说的话),可能需要
一些技巧。
project-build/
project/
CMakeLists.txt (whole project CMakeLists.txt)
[
project(MyAwesomeProject)
include_directories(include) # allow lib1 and lib2 to include lib1/lib.h and lib2/lib.h
add_subdirectory(lib1) # this adds target lib1
add_subdirectory(lib2) # this adds target lib2
]
lib1/ (first library)
CMakeList.txt
[
add_library(lib1...)
add_subdirectory(test)
]
src/
lib1.c
foo1.h
test/ (tests)
CMakeList.txt
test1.c
test2.c
lib2/ (second library)
CMakeList.txt
[
add_subdirectory(src)
]
src/
CMakeList.txt
[
if(WIN32)
set(lib2_os_sources os/win32/xxx.c)
elsif(LINUX)
set(lib2_os_sources os/linux/xxx.c)
else()
message(FATAL_ERROR "Unsupported OS")
endif()
add_library(lib2 SHARED lib2.c ${lib2_os_sources})
]
os/ (OS dependent code)
win32/
xxx.c (win32 implementation)
linux/
xxx.c (linux implementation)
lib2.c
foo2.h
include/ (shared/public headers)
lib1/
lib.h (shared library header included from apps)
lib2/
lib.h (shared library header -"-)