Ask Your Question

publisher and rosinit

asked 2011-09-28 07:50:40 -0500

kang gravatar image


I have a small coding problem while writing publisher. Usually I write publisher inside main function in my code:


after initialize ros, create nodhandle, and define publisher. Similar like this tutorial).

Now, I trying to publish not in my main function. But this could not work since the ros initialization and nodeHandle etc are in main function. And if I write the nodehandle in my one of my subfunction, the nodehandle will also directly off after the subfunction being called.

I was thinking if the rosinit could be initialized before the main function, but still have found the way.

Let me now if someone have suggestion. Thx

Cheers, Kang

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted

answered 2011-09-28 11:28:45 -0500

KoenBuys gravatar image

You want the publisher to be declared as a global object. You create the node handle in your start up routine/constructor and initialise the publisher from that.

 //globally defined
 ros::Publisher pub_;

 //in your constructor
 int main(int argc, char** argv){
 pub_ = nh_.advertise<PointCloud> ("points2", 1);
edit flag offensive delete link more

answered 2011-09-29 19:24:47 -0500

If you don't like global variables, you can also pass the publisher by reference to a function:

void worker (ros::Publisher& pub)

int main (int argc, char** argv)
  ros::NodeHandle nh;
  ros::Publisher pub = nh.advertise<PointCloud>("points2", 1);
edit flag offensive delete link more

answered 2011-09-28 08:07:31 -0500

Make the node handle a global or class variable so you can reference it from anywhere. You can declare the node handle, without initializing it, then do the initialization in your main function.

edit flag offensive delete link more


the nodeHandle can be set globlally? I think I have tried that one, but I'll check again soon.
kang gravatar image kang  ( 2011-09-28 08:09:05 -0500 )edit
creating nodeHandle before ros initialization is not allowed. But, I made it work by defining variable in a class.
kang gravatar image kang  ( 2011-09-28 19:26:12 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2011-09-28 07:50:40 -0500

Seen: 3,290 times

Last updated: Sep 29 '11