We would like to organize a C++
project like this:
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 -"-)
Please, how to write those CMakeLists.txt
when even lib2
should use link1
and when e.g. lib2
should be portable (at least Win32, Linux...)?
Correction: If some CMakeList.txt
files are not on their places, please assume so. I probably forgot.
The whole philosophy is to start with a central CMakeLists.txt for your whole project. At this level all the targets (libs, executables) are gonna be aggregated so there will be no problem linking from lib1 to lib2 for example. If lib2 is gonna be linking to lib1, lib1 needs to be built first.
Platform specific source files should be set conditionally to some variable.
(If you need to set variable in a subdirectory and use it in a directory above, you have to set it to the cache, using CACHE FORCE etc. - see manual for set
)
This is how you do proper out of source build - as CMake intends:
cd project-build
cmake ../project
Having separate build directories per library is not very CMake'ish (if I may say so) and would probably require
some hacks.
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 -"-)