- CMake Cookbook
- Radovan Bast Roberto Di Remigio
- 204字
- 2025-04-04 16:17:17
How to do it
These two new files will also have to be compiled and we have to modify CMakeLists.txt accordingly. However, in this example we want to compile them first into a library, and not directly into the executable:
- Create a new target, this time a static library. The name of the library will be the name of the target and the sources are listed as follows:
add_library(message
STATIC
Message.hpp
Message.cpp
)
- The creation of the target for the hello-world executable is unmodified:
add_executable(hello-world hello-world.cpp)
- Finally, tell CMake that the library target has to be linked into the executable target:
target_link_libraries(hello-world message)
- We can configure and build with the same commands as before. This time a library will be compiled, alongside the hello-world executable:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
Scanning dependencies of target message
[ 25%] Building CXX object CMakeFiles/message.dir/Message.cpp.o
[ 50%] Linking CXX static library libmessage.a
[ 50%] Built target message
Scanning dependencies of target hello-world
[ 75%] Building CXX object CMakeFiles/hello-world.dir/hello-world.cpp.o
[100%] Linking CXX executable hello-world
[100%] Built target hello-world
$ ./hello-world
This is my very nice message:
Hello, CMake World!
This is my very nice message:
Goodbye, CMake World