ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

I think this statement in your original post is probably false:

I think I cannot define a publisher outside a main() file because main would consist of Nodehandler and other important ros features.

ROS creates one node for each executable process. This is set up by your ros::init() call. You can then create as many NodeHandle as you want. Each NodeHandle points to the same underlying ROS node. It's typical to create a single NodeHandle and re-use it wherever needed, but that's not a requirement. The only requirement is that you must call ros::init() before creating any NodeHandle objects.

So, if needed, you can just create a new NodeHandle inside your function and use that to construct the publisher you need. Note that this may not be the best design, if your function is called frequently. Creating a new NodeHandle is cheap, but creating a new publisher involves advertising a new topic to the ROS master and connecting to any subscriber nodes, which can be "expensive".

If you call the function each time you want to publish a new message, then you should declare the publisher external to the function: - as a global var (use a boost::shared_ptr<ros::publisher> to make sure it gets created after the ros::init() call) - as a class member variable - passed to the function by reference (probably the easiest) - passed to the function by boost::shared_ptr<ros::publisher>