Include methods from another node header (C++)
I have a node with some methods declared in /include/node_1.h
and defined in /src/node_1.cpp
. Now, I want to include that header into another node /src/node_2.cpp
and use the methods there, like:
// node_2.cpp
#include "pkgname/node_1.h"
// ...
some_method_from_node_1();
I can catkin_make
with including, but I get a linker error (undefined reference to the method) when trying to compile while calling the method from node_2.
My CMakeLists.txt
for the package looks like:
# ...
## declare a catkin package
catkin_package(
INCLUDE_DIRS include
CATKIN_DEPENDS message_runtime
)
## include dirs
include_directories(include ${catkin_INCLUDE_DIRS})
## nodes
set(NODES
node_1
node_2
)
foreach(node IN LISTS NODES)
add_executable(${node} src/${node}.cpp)
target_link_libraries(${node} ${catkin_LIBRARIES})
add_dependencies(${node} hric_sys_generate_messages_cpp)
endforeach()
How can I make it work and is this approach even idiomatically correct?
EDIT:
So, I have a method called my_test_func()
, which I can call from node_1
but get a linker error if I try to invoke it from node_2
, although the include works. This is the (simplified) code:
include/node_1.h
:
# pragma once
void my_test_func();
src/node_1.cpp
:
#include "package/node_1.h"
void my_test_func()
{
ROS_INFO("API CALL!");
}
int main()
{
// ...
my_test_func(); // WORKS
}
src/node_2.cpp
:
#include "package/node_1.h"
int main()
{
// ...
my_test_func(); // DOESN'T WORK
}
So the linker can't find the function. Are you sure that the function is defined correctly and that it can be called. E.g. can you call it in node_1? If you also put your header and source files here, it is more easy to answer your question.
It worked from node_1, yes, and I could include the method in node_2. I didn't upload the full code, because I simplified the problem with different names. I think the error might have been making the method definition in node_1
inline
. I will check that on Monday.So, I added some example code below.. It still doesn't work, even if the method is not inlined.