Search code examples
c++cmakeroscatkin

CMake How to properly include my own headers?


I am working with ros and now I want to write my own unittest. But I am struggling with it. Maybe you have an suggestion for me? Or maybe a solution?

my structure:
-catkin_ws
--build
--install
--src
----project1
----CMakeLists.txt
----package.xml
------include
--------prime_tables.h
--------sample1.h
------src
--------sample1.cpp
------tests
--------sample1_unittest.cpp

my cmakelist.txt:

cmake_minimum_required(VERSION 2.8.3)
project(project1)

find_package(catkin REQUIRED COMPONENTS roscpp rostest rosunit)
find_package(sample1)



catkin_package(
   INCLUDE_DIRS include
   LIBRARIES ${PROJECT_NAME}
   CATKIN_DEPENDS roscpp rostest
   DEPENDS  )
include_directories(include ${catkin_INCLUDE_DIRS})


if (CATKIN_ENABLE_TESTING)
  catkin_add_gtest(project1 tests/sample1_unittest.cpp)

  add_executable(add_test tests/sample1_unittest.cpp)
  add_library(add include/sample1.h src/sample1.cpp)
  target_link_libraries(add_test ${catkin_LIBRARIES})
  target_link_libraries(add_test gtest)
  target_link_libraries(add_test prime_tables)
  target_link_libraries(add_test sample1)
endif()

I receive this error:

[87%] Linking CXX exectuable

/usr/bin/ld -lprime_tables cannot find
/usr/bin/ld -lsample1 cannot find

What is the problem? You mention it, I am not very familiar with CMake.


Solution

  • In sample1.cpp is a library you want and to test and you want to create an executable which links to this library and runs a unit test?

    Some basic cmake info: The first argument of add_library, add_executable and target_link_libraries is the name of the library/executable. So if you specify your linked librarys to this library or executable you have to use this name again.

    And look here for more information: http://wiki.ros.org/catkin/CMakeLists.txt http://docs.ros.org/jade/api/catkin/html/howto/format2/gtest_configuration.html

    My guess is, that you want a cmake like this:

    cmake_minimum_required(VERSION 2.8.3)
    project(project1)
    
    catkin_package(
      INCLUDE_DIRS include
      LIBRARIES ${PROJECT_NAME}
      CATKIN_DEPENDS roscpp rostest
      DEPENDS
    )
    include_directories(include 
      ${catkin_INCLUDE_DIRS}
    )
    
    add_library(${PROJECT_NAME}_sample1 
      src/sample1.cpp
    )
    target_link_libraries(
      ${PROJECT_NAME}_sample1
      ${catkin_LIBRARIES}
    )
    
    if (CATKIN_ENABLE_TESTING)
      catkin_add_gtest(${PROJECT_NAME}_test 
        tests/sample1_unittest.cpp
      )
      target_link_libraries(${PROJECT_NAME}_test 
        ${PROJECT_NAME}_sample1
        ${catkin_LIBRARIES}
      )
    endif()