
上QQ阅读APP看书,第一时间看更新
How to do it
This is a C project and we will use the C99 standard. We will build the CMakeLists.txt file step by step:
- We declare a C project and enforce compliance with the C99 standard:
cmake_minimum_required(VERSION 3.6 FATAL_ERROR)
project(recipe-09 LANGUAGES C)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_C_STANDARD_REQUIRED ON)
- We look for pkg-config, using its find-module shipped with CMake. Notice the QUIET argument passed to find_package. CMake will print messages only if the required pkg-config is not found:
find_package(PkgConfig REQUIRED QUIET)
- When pkg-config is found, we will have access to the pkg_search_module function to search for any library or program that ships a package configuration .pc file. In our case, we look for the ZeroMQ library:
pkg_search_module(
ZeroMQ
REQUIRED
libzeromq libzmq lib0mq
IMPORTED_TARGET
)
- A status message is printed, in case the ZeroMQ library was found:
if(TARGET PkgConfig::ZeroMQ)
message(STATUS "Found ZeroMQ")
endif()
- We can then add the two executable targets and link against the IMPORTED target for ZeroMQ. This will set include directories and link libraries automatically:
add_executable(hwserver hwserver.c)
target_link_libraries(hwserver PkgConfig::ZeroMQ)
add_executable(hwclient hwclient.c)
target_link_libraries(hwclient PkgConfig::ZeroMQ)
- Now, we can configure and build the example:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
- In one terminal, start the server, which will respond with a message similar to this example:
Current 0MQ version is 4.2.2
- Then, in another terminal start the client, which will print the following:
Connecting to hello world server…
Sending Hello 0…
Received World 0
Sending Hello 1…
Received World 1
Sending Hello 2…
...