[CMake] Write CMakeLists.txt for this C++ program

Eric Dönges doenges at mvtec.com
Wed Jun 19 07:58:47 EDT 2019


On 19.06.19 12:42, dexter810 wrote:
> cmake_minimum_required(VERSION 3.6)
> project(main CXX C)
> 
> add_executable(main main.cpp)
> 
> set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Iinclude
> -Ibuild/deps/yara/src/yara/libyara/include -Lbuild/src
> -Lbuild/deps/yara/src/yara/libyara/.libs/")
> 
> 
> target_link_libraries (main yaracpp yara pthread ssl crypto)
> 
> 
> But this was not able to link it properly and threw errors that it cannot
> find "yaracpp/yaracpp.h". The references for writing CMakeLists.txt like
> this were: 
> 
> https://stackoverflow.com/questions/43136418/how-to-add-l-ell-compiler-flag-in-cmake
> 
> https://stackoverflow.com/questions/53879422/how-to-set-g-compile-options-in-clion?answertab=oldest#tab-top

Since you don't include the error messages from the compiler, we are
reduced to guessing here:

1) Don't add -I flags to compiler command line by modifying the
CMAKE_CXX_FLAGS directly. Instead, use either the include_directories
command (if you want to specify the include directories for multiple
targets), or the target_include_directories command:

	target_include_directories(main PRIVATE
		include build/deps/yara/src/yara/libyara/include)

2) CMAKE_CXX_FLAGS is used for compiling, not linking. One way to get
the linker command line you want is to change

	target_link_libraries (main yaracpp yara pthread ssl crypto)

to

	target_link_libraries (main
		-Lbuild/src build/deps/yara/src/yara/libyara/.libs
		-lyaracpp -lyara pthread ssl crypto)

However, better practice would be to create import targets for the
libraries you want to use. For example (assuming that yaracpp is a
shared library):

	add_library(yaracpp SHARED IMPORTED)
	set_target_properties(yaracpp PROPERTIES
		IMPORTED_LOCATION "build/deps/yara/src/yara/libyara/.libs/libyara.so"
		INTERFACE_INCLUDE_DIRECTORIES "build/deps/yara/src/yara/libyara/include")

Then, you simply add yaracpp to your target_link_libraries command and
can skip the target_include_directories command. Even better practice
would be to use the find_library command to find the libyara library -
this way, your CMakelists.txt would also work for non-Unix target
systems like Windows.

For more information, I highly recommend reading the CMake
documentation, particularly
https://cmake.org/cmake/help/v3.15/manual/cmake-buildsystem.7.html


More information about the CMake mailing list