Ask Your Question

how to put subscriber and publisher in one cpp file ?

asked 2011-12-11 04:50:01 -0500

maruchi gravatar image

Hi, I have a limited knowledge in C++ so that feel a difficulty in combining a subscriber and a publisher in one C++ file. Based on the tutorial, , could anybody give some directions on making one C++ file which includes a subscriber and a publisher ?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2011-12-11 10:57:00 -0500

karthik gravatar image

Hi, Like there is 1 subscriber and 1 publisher in the tutorial. Try to write 2 chatters. i.e each chatter should be able to listen and also talk. In the subscriber of the tutorial add a publisher with different topic. Here is example code. I haven't executed it but it should be simple enough to understand.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>

void chatterCallback(const std_msgs::String::ConstPtr& msg)
  ROS_INFO("I heard: [%s]", msg->data.c_str());

int main(int argc, char **argv)

  ros::init(argc, argv, "listener");   
  ros::NodeHandle n;   
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("different_chatter", 1000);

  ros::Rate loop_rate(10);   

  int count = 0;
  while (ros::ok())

    std_msgs::String msg;

    std::stringstream ss;
    ss << "hello world " << count; = ss.str();






  return 0;

Now you can write the second chatter listening to "different_chatter" and publishing to "chatter" topics. Hope this helps,


edit flag offensive delete link more


Karthik, thanks for your help. If it is possible, could you put some comment to my question on here,
maruchi gravatar image maruchi  ( 2011-12-11 14:23:37 -0500 )edit

answered 2016-01-21 06:03:58 -0500

sxin gravatar image
edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

1 follower


Asked: 2011-12-11 04:50:01 -0500

Seen: 8,769 times

Last updated: Dec 11 '11