Subscriber and publisher in one file in ROS
<p>How to make a subscriber and publisher in ROS on C++ in one file? I tried this and publisher works but subscriber callback function is not called</p>

<pre><code>#include &lt;ros/ros.h&gt;
#include &lt;iostream&gt;
#include &lt;std_msgs/UInt16.h&gt;
#include &lt;math.h&gt;

int error = 0;

void error_sub(const std_msgs::UInt16::ConstPtr&amp; msg)
 {
    ROS_INFO("I heard: [%d]", msg-&gt;data);
    error = msg-&gt;data;
 }

int main(int argc, char** argv)
{
    ros::init(argc, argv, "lighter");
    ros::NodeHandle nh;

    ros::Publisher connected =nh.advertise&lt;std_msgs::UInt16&gt;("/robot/sonar/head_sonar/lights/set_lights",1);

    ros::Subscriber sub = nh.subscribe("/plc/error", 1000, error_sub);
    std_msgs::UInt16 msg;

    while(ros::ok())
    {
        if(error &gt;= 0)
        {
            msg.data = 36863;
            connected.publish(msg);
        }
        ros::spinOnce();
    }
}
</code></pre>