ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The problem is because you declare and define the service within the function testFunction, so once the function is finished the service goes out of scope and doesn't exist anymore.

If you sleep some time in your function you will see that the service exists while you are still in the function :

void testFunction(ros::NodeHandle &n)
  ros::ServiceServer service = n.advertiseService("add_two_ints", add);
  ros::Rate r(0.2); //Sleep for 5 seconds

About your issue :

In my use case, I need to set up a service in a separate file.

I'm not sure to get why setting up a service in a separate file requires you to use a function like in your example. Maybe you could add more details about this. I would recommend creating a class in your separate file that would have ros::ServiceServer as member so that when you create an instance of this class in your main the service is kept alive.