how to split 'header', 'src', 'test' dir in cmake?(and donot add cmakelist.txt in each dir) - cmake

when building a project stucture like following:
LinearAlgebra
|---HEADER
|-----|---Linear.h
|---SRC
|-----|---Linear.cpp
|---TEST
|-----|---hello_test.cc
here is my CMakeList.txt:
cmake_minimum_required(VERSION 3.10)
project(LinearAlgebra )
set(CMAKE_CXX_STANDARD 11)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
add_library(LA_HEADER INTERFACE header/Linear.h)
add_library(LA_SRC INTERFACE src/Linear.cpp)
target_include_directories(LA_HEADER INTERFACE "${PROJECT_SOURCE_DIR}/header" "${PROJECT_SOURCE_DIR}/src")
enable_testing()
add_executable(
hello_test
test/hello_test.cc
)
target_link_libraries(
hello_test
gtest_main
LA_HEADER
LA_SRC
)
include(GoogleTest)
gtest_discover_tests(hello_test)
it works fine with cmake -S . -B build, but when it comes to cmake --build build following error occured:
Undefined symbols for architecture x86_64:
"Linear::Linear()", referenced from:
HelloTest_BasicAssertions_Test::TestBody() in hello_test.cc.o
it seems something wrong with my cmake file that didn't tell Linear.h where Linear.cpp located. So how to fix it ?? thanks for your help...

seems i misunderstand add_library, change three lines and it works out:
cmake_minimum_required(VERSION 3.10)
project(LinearAlgebra )
include_directories(header) # include_directories instead of add_library for .h files
add_library(LA_LIB src/Linear.cpp) # use add_library for .cpp files only!!!
set(CMAKE_CXX_STANDARD 11)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(
hello_test
test/hello_test.cc
)
target_link_libraries(
hello_test
gtest_main
LA_LIB # link LA_LIB only..
)
include(GoogleTest)
gtest_discover_tests(hello_test)
leave it here for anyone have the same requirements.

Related

Modify CMakeLists.txt for googletests in order to use googlemock

I was checking the quickstarter to use googletest with cmake. I was wondering how I should modify the CMakeLists.txt they provide (given below) in order to use googlemock.
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(
hello_test
hello_test.cc
)
target_link_libraries(
hello_test
GTest::gtest_main
)
include(GoogleTest)
gtest_discover_tests(hello_test)
for the moment, #include <gtest/gtest.h> works but #include <gmock/gmock.h> doesn't
GMock should be available via GTest::gmock cmake target. At least this is the target name used in the cmake configuration files of a GTest build installed via cmake.
target_link_libraries(
hello_test
GTest::gmock
)

CMake - How to get include directories of external project?

I tried to used https://github.com/julianxhokaxhiu/SteamworksSDKCI to use steam api on a simple SFML application (helloworld).
I wanted to use cmake to learn it, but I am struggling to understand how the provided CMakeLists and Find*.cmake file are expected to be used.
Currently, I have modified the CMakeLists to change the INSTALL_DIR
INSTALL_DIR "${CMAKE_BINARY_DIR}/../../vendor"
and my CMakeLists is :
cmake_minimum_required(VERSION 3.19)
project(SfmlWithCMake VERSION 1.0)
include(FetchContent)
set (CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${CMAKE_CURRENT_SOURCE_DIR}/cmake_steam")
# Configure external project
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/cmake_steam)
execute_process(
COMMAND ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR}/cmake_steam
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/cmake_steam
)
# Build external project
execute_process(
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}/cmake_steam
)
set(BUILD_SHARED_LIBS OFF)
FetchContent_Declare(
SFML
GIT_REPOSITORY https://github.com/SFML/SFML.git
GIT_TAG 2.5.1
)
FetchContent_MakeAvailable(SFML)
find_package(STEAMWORKSSDK REQUIRED)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED true)
# Generate config.h
configure_file(config.h.in config.h)
add_executable(
SfmlWithCMake
main.cpp
)
get_target_property(STEAMSDK STEAMWORKSSDK::STEAMWORKSSDK INCLUDE_DIRECTORIES)
target_include_directories(
SfmlWithCMake
PRIVATE
"${PROJECT_BINARY_DIR}"
"${STEAMSDK}"
)
target_link_libraries(
SfmlWithCMake
sfml-graphics
STEAMWORKSSDK::STEAMWORKSSDK
-static gcc stdc++ winpthread -dynamic
)
install(TARGETS SfmlWithCMake DESTINATION bin)
How to get include directories?
I do not succeed to add the steam include to the target_include_directories.
Here the ${STEAMSDK} is my last attempt to get the directory.
If I replace this by ${PROJECT_BINARY_DIR}/vendor/include, everything works.
Also, why does the SFML include are automatically added to my target include directories and not the steam one?
Am I using the Find*.cmake file the right way?
I understood that ExternalProject_Add was performed at build time and thus, as the find_package is needed at configue time, I added the two "execute_process". But, the readme on github only says to do the find package and add the target to target_link_libraries...
Thanks.

How to add include directories from ExternalProject_Add into project?

I have tried following this solution this individual has from this question. I am trying to do this with boost with the following cmake file in a separate directory from my Source:
#---------------------------------------------------------------------------
# Get and build boost
SET_PROPERTY(DIRECTORY PROPERTY "EP_BASE" ${ep_base})
SET(boost_GIT_TAG "origin/master")
set( Boost_Bootstrap_Command )
if( UNIX )
set( Boost_Bootstrap_Command ./bootstrap.sh )
set( Boost_b2_Command ./b2 )
else()
if( WIN32 )
set( Boost_Bootstrap_Command bootstrap.bat )
set( Boost_b2_Command b2.exe )
endif()
endif()
ExternalProject_Add(Boost_external_Download
GIT_REPOSITORY "https://github.com/boostorg/boost.git"
GIT_TAG ${boost_GIT_TAG}
BUILD_IN_SOURCE 1
UPDATE_COMMAND ""
PATCH_COMMAND ""
CONFIGURE_COMMAND ${Boost_Bootstrap_Command}
BUILD_COMMAND ${Boost_b2_Command} install
--without-python
--without-mpi
--disable-icu
--prefix=${CMAKE_BINARY_DIR}/Boost
--threading=single,multi
--link=shared
--variant=release
-j8
INSTALL_COMMAND ""
INSTALL_DIR ""
)
if( NOT WIN32 )
set(Boost_LIBRARY_DIR ${CMAKE_BINARY_DIR}/Boost/lib/ )
set(Boost_INCLUDE_DIR ${CMAKE_BINARY_DIR}/Boost/include/boost/ )
else()
set(Boost_LIBRARY_DIR ${CMAKE_BINARY_DIR}/Boost/lib/ )
set(Boost_INCLUDE_DIR ${CMAKE_BINARY_DIR}/Boost/include/boost/ )
endif()
ExternalProject_Get_Property(Boost_external_Download BINARY_DIR)
SET(Boost_DIR ${BINARY_DIR} CACHE PATH "")
add_library(Boost_external SHARED IMPORTED)
The only thing that is different between one of the solutions and mine is that I don't have the set_target_properties right after I add the library. Since boost has a lot of libraries in there and I am not exactly sure what needs to be added.
In my Source Folder, my CMakeLists.txt does the following:
include_directories(${Boost_INCLUDE_DIR})
add_executable(Main main.cpp)
target_link_libraries(Main Boost_external)
add_dependencies(Main Boost_external_Download)
However, in main.cpp when I use #include <boost/process.hpp> just to see if it links, I get the error that #include <boost/process.hpp> no such file or directory. When I try to make the project. I am not really sure where I am going wrong with this so any helpful advice would be appreciated.
Edit: structure
Root Folder
|
- CmakeLists.txt
- Externals Directory
|
| - Externals.cmake
| - boostExternal.cmake
| - other external cmake files
- Source Directory
|
| - CmakeLists.txt
| - main.cpp
The Root Cmake calls the Externals.cmake file. Which then includes all the other Cmake files within that directory. Once those are finished, the root Cmake file add the directory Source, and that Cmake file has the call to include_directories(${Boost_INCLUDE_DIR}).

Unix make file fails with cmakejs when adding a dependency

I successfully created a native node addon with napi and cmakejs. But when adding a simple library the unix make file, generated by cmake-js explodes with
[ 50%] Linking CXX static library liblib_name.a
[ 50%] Built target lib_name
CMakeFiles/spielwiese.dir/flags.make:10: * missing separator. Stop.
make[1]: * [CMakeFiles/Makefile2:72: CMakeFiles/spielwiese.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
ERR! OMG Process terminated: 2
Minimized example project: https://github.com/Superlokkus/spielwiese/tree/napi
The root CMakeLists should be close or intented to be close to cmakejs example boilerplate version, just with an additional function PARSE_CMAKEJS_PROPERTIES to also build it via a cmake CLI command, for nice developing with IDEs like CLion. However the problem persisits when removing the PARSE_CMAKEJS_PROPERTIES function.
I added the library with a add_subdirectory, if you remove https://github.com/Superlokkus/spielwiese/blob/napi/CMakeLists.txt#L47 aka add_subdirectory(src/lib_name) and change https://github.com/Superlokkus/spielwiese/blob/napi/CMakeLists.txt#L63 aka target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_JS_LIB} lib_name) to target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_JS_LIB}) and also remove
https://github.com/Superlokkus/spielwiese/blob/napi/src/spielwiese.cpp#L3 aka #include <lib_name/lib_name.hpp>,
the project builds again incl. the mocha test. However add the example library and you get the error again.
Root CMakeLists:
cmake_minimum_required(VERSION 3.2)
# The following function is just for nice CLion IDE support with cmake-js
function(PARSE_CMAKEJS_PROPERTIES)
function(GET_VARIABLE INPUT_STRING VARIABLE_TO_SELECT OUTPUT_VARIABLE)
set(SEARCH_STRING "${VARIABLE_TO_SELECT}=\"")
string(LENGTH "${SEARCH_STRING}" SEARCH_STRING_LENGTH)
string(LENGTH "${INPUT_STRING}" INPUT_STRING_LENGTH)
string(FIND "${INPUT_STRING}" "${VARIABLE_TO_SELECT}=\"" SEARCH_STRING_INDEX)
math(EXPR SEARCH_STRING_INDEX "${SEARCH_STRING_INDEX}+${SEARCH_STRING_LENGTH}")
string(SUBSTRING "${INPUT_STRING}" ${SEARCH_STRING_INDEX} ${INPUT_STRING_LENGTH} AFTER_SEARCH_STRING)
string(FIND "${AFTER_SEARCH_STRING}" "\"" QUOTE_INDEX)
string(SUBSTRING "${AFTER_SEARCH_STRING}" "0" "${QUOTE_INDEX}" RESULT_STRING)
set("${OUTPUT_VARIABLE}" "${RESULT_STRING}" PARENT_SCOPE)
endfunction(GET_VARIABLE)
string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER)
if (CMAKE_BUILD_TYPE_LOWER STREQUAL "debug")
exec_program(./node_modules/.bin/cmake-js ${CMAKE_CURRENT_SOURCE_DIR}
ARGS print-configure --debug
OUTPUT_VARIABLE CMAKE_JS_OUTPUT
)
else ()
exec_program(./node_modules/.bin/cmake-js ${CMAKE_CURRENT_SOURCE_DIR}
ARGS print-configure
OUTPUT_VARIABLE CMAKE_JS_OUTPUT
)
endif ()
get_variable("${CMAKE_JS_OUTPUT}" "CMAKE_JS_INC" CMAKE_JS_INC)
set(CMAKE_JS_INC "${CMAKE_JS_INC}" PARENT_SCOPE)
get_variable("${CMAKE_JS_OUTPUT}" "CMAKE_LIBRARY_OUTPUT_DIRECTORY" CMAKE_LIBRARY_OUTPUT_DIRECTORY)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}" PARENT_SCOPE)
endfunction(PARSE_CMAKEJS_PROPERTIES)
# Name of the project (will be the name of the plugin)
project(spielwiese VERSION 1.0)
if (NOT CMAKE_JS_INC)
parse_cmakejs_properties()
endif ()
add_subdirectory(src/lib_name)
# Essential include files to build a node addon,
# you should add this line in every CMake.js based project.
include_directories(${CMAKE_JS_INC})
# Declare the location of the source files
file(GLOB SOURCE_FILES "src/*.cpp")
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES})
# This line will give our library file a .node extension without any "lib" prefix
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
# Essential library files to link to a node addon,
# you should add this line in every CMake.js based project.
target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_JS_LIB} lib_name)
# Include N-API wrappers
execute_process(COMMAND node -p "require('node-addon-api').include"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE NODE_ADDON_API_DIR
)
string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})
Libnames CMakeLists
cmake_minimum_required(VERSION 3.0)
project(lib_name VERSION 1.0)
string(TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPER_CASE)
configure_file(
${PROJECT_NAME}_version.hpp.in
${PROJECT_SOURCE_DIR}/include/${PROJECT_NAME}/${PROJECT_NAME}_version.hpp
)
set(${PROJECT_NAME}_implementation_files
src/lib.cpp
)
add_library(${PROJECT_NAME} ${${PROJECT_NAME}_implementation_files})
set_property(TARGET ${PROJECT_NAME} PROPERTY LINKER_LANGUAGE CXX)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 17)
target_include_directories(${PROJECT_NAME}
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
install(TARGETS ${PROJECT_NAME}
ARCHIVE
DESTINATION lib)
install(TARGETS ${PROJECT_NAME}
PUBLIC_HEADER
DESTINATION include)
Update
I did some experimentation and it seems
target_include_directories(${PROJECT_NAME}
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
is doing the trouble, so it looks like cmakejs has some problem with that command?!
Turns out the snippet taken from the official cmake-js documentation
execute_process(COMMAND node -p "require('node-addon-api').include"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE NODE_ADDON_API_DIR
)
is invoking node to get the path to the node headers. But the output of node might contain a newline, which will ruin the day of all includes after that. So the correct part of the root CMakeLists.txt would be
# Include N-API wrappers
execute_process(COMMAND node -p "require('node-addon-api').include"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE NODE_ADDON_API_DIR
)
string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})
So a addition of string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR}) to get rid of the newline fixed the problem.
Thanks #fred for the help to find the problem
Already created a pull request to fix the cmake-js documentation: https://github.com/cmake-js/cmake-js/issues/175

CLion parses GCC errors?

I have a few CMake targets in my project that calls makefiles, which will call gcc.
When there is a build error it shows up on Messages>Build:
my_dir/my_file.c: In function 'my_func':
my_dir/my_file.c.c:52:5: error: expected ';' before '}' token
I wanted to click on it and go straight to my_dir/my_file.c.c:52:5, is that possible?
My Cmakelists.txt only has symbols and include folders for indexing purposes, no C build configuration since all of that is made in the makefiles.
EDIT
This is my CMakeLists.txt structure:
cmake_minimum_required(VERSION 3.7)
project(myexec)
set(CMAKE_CXX_STANDARD 99)
set(MakefileDir ${CMAKE_CURRENT_SOURCE_DIR}/make)
add_custom_target(
mytarget
ALL
WORKING_DIRECTORY ${MakefileDir}
COMMAND make all)
file(GLOB_RECURSE SRCS *.c)
file(GLOB_RECURSE HDRS *.h)
include_directories(
sometthing/inc
(...)
)
add_definitions(
-DMY_SYM=1
(...)
)
add_executable(myexec EXCLUDE_FROM_ALL ${SRCS} ${HDRS})