ROS C++ in 5 days Publisher Error

This is the code that I am running for publisher:

#include <ros/ros.h>
#include <std_msgs/Int32.h>

int main (int argc, char **argv){

ros::init(argc, argv, "topic_publisher");
ros::NodeHandle nh;

ros::Publisher pub = nh.advertise<std_msgs::Int32>("counter", 1000);
ros::Rate loop_rate(2);

std_msgs::Int32 count; = 0;

while (ros::ok())
return 0;


Error i am getting:
/home/user/catkin_ws/src/topic_publisher_pkg/src/simple_topic_publisher.cpp: line 5: syntax error near unexpected token (' /home/user/catkin_ws/src/topic_publisher_pkg/src/simple_topic_publisher.cpp: line 5: int main (int argc, char **argv){’

Hello @nihal.navale22 welcome to the community!

What is the exercise number you are at? Also, could you please confirm that you saved your .cpp file, made the corresponding changes to the CMakeLists.txt fie and then executed catkin make form inside the ~catkin_ws/ folder?

Then please post the command that you are running to start the executable.



I am at the 3rd unit and I have made the following changes in the Cmakelist:

add_executable(simple_topic_publisher src/simple_topic_publisher.cpp)
add_dependencies(simple_topic_publisher ${simple_topic_publisher_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(simple_topic_publisher ${catkin_LIBRARIES})

I have saved the files and i used catkin_make to build and rosrun topic_publisher_pkg simple_topic_publisher.cpp

Hello @nihal.navale22,

thanks for the updated information. I tested it and I can conform that I am running the exercise without issues.

One thing that I noticed is that you are using the command:

rosrun topic_publisher_pkg simple_topic_publisher.cpp

However the correct command is without the .cpp at the end:

rosrun topic_publisher_pkg simple_topic_publisher

I could not reproduce the error you are getting thought.

My suggestion now is to remove the package you created by doing so:

cd ~catkin_ws/src
rm -rf topic_publisher_pkg

Then you start from scratch.

1.- Create a new package inside ~catkin_ws/src
2.- Fill in the source code
3.- Modify the CMakeLists.txt file
4.- Go to ~catkin_ws and run catkin_make, then source devel/setup.bash
5.- Finally execute your program using rosrun topic_publisher_pkg simple_topic_publisher

Hope this gets you unstuck,



I found the solution,
Just like you had mentioned, I had to remove the .cpp extension when running the rosrun command
The other issue was that ROS was not finding the newly made package, so I run the command $ rospack profile
and checked with the command $ rospack find
Works now!

Hi @nihal.navale22,

I glad to hear you got it solved!