The add_library function’s signature is add_library(target, STATIC/SHARED [src files...]), meaning to use all src files to compile the static/dynamic target library.
Then, target_link_libraries(a.out PUBLIC hellolib) links the hellolib‘s source to the a.out.
If the main.cpp uses the headers in the subdirectory hellolib, then main.cpp should write #include "hellolib/hello.h". To simplify the #include statement, we could add the following to main’s CMakeLists.txt:
1 2 3 4
... add_executable(a.out main.cpp) target_include_directories(a.out PUBLIC hellolib) ...
This is still some complex. If we want to build two executable, we need write the following, with repeated code:
1 2 3 4 5 6
... add_executable(a.out main.cpp) target_include_directories(a.out PUBLIC hellolib) add_executable(b.out main.cpp) target_include_directories(b.out PUBLIC hellolib) ...
A solution is to move the target_include_directories() to the subdirectory. Then all the further library/executable relied on the hellolib will include this subdirectory.
1 2
# sub-directory target_include_directories(hellolib PUBLIC .)
If we change the PUBLIC to PRIVATE, then the further dependent would not have the effects.
Link existing library
For example, use the following code to link the OpenMP library.
1 2
find_package(OpenMP REQUIRD) target_link_libraries(main PUBLIC OpenMP::OpenMP_CXX)
Use the following code to link the OpenMP library.
set(CMAKE_BUILD_TYPE Release) # Or set it when building cmake --build build --config Release
Set C++ standard:
1
SET(CMAKE_CXX_STANDARD 17)
Set global / special macros:
1 2 3 4 5 6 7 8 9
# global add_definitions(-DDEBUG) # -D is not necessary add_definitions(DEBUG) # special target target_compile_definitions(a.out PUBLIC -DDEBUG) target_compile_definitions(a.out PUBLIC DEBUG)
# They have the same effect as g++ xx.cpp -DDEBUG # (define a `DEBUG` macro to the file)
Set global / special compiling options:
1 2 3 4 5 6 7
# global add_compile_options(-O2) # special target target_compile_options(a.out PUBLIC -O0)
# They have the same effect as g++ xx.cpp -O0 # (add a `-O0` option in the compilation)
1 2
# Set SIMD and fast-math target_compile_options(a.out PUBLIC -ffast-math -march=native)
Set global / special include directories:
1 2 3 4
# global include_directories(hellolib) # special target target_include_directories(a.out PUBLIC hellolib)
CUDA with CMake
A common template can be:
1 2 3 4 5 6 7 8 9
cmake_minimum_required(VERSION 3.10) project(main LANGUAGES CUDA CXX)