Python vs C++ – How to run Python and C++ code in ROS
Python vs C++ – see the major difference between running code in the two major languages used by ROS. Let’s go!
Step 1: Create an account and Login to Robot Ignite Academy
On Robot Ignite Academy, you get access to the best online ROS courses and environment. No need to install and set up ROS locally – the only thing you need is a browser!
- Create an account or log in here.
- Launch the ROS Basics in 5 Days Python course.
- You’ll now have access to the simulation screen with a Notebook, an Editor, four Shells, and a Simulation Window. We are only using the Editor and Shells for this demo.
Step 2: Create a ROS package and some Python and C++ code
2. 1 Create a package by typing the following command in the shell
cd ~/catkin_ws/src catkin_create_pkg obiwan rospy roscpp
2.2 Then in the src
folder under the obiwan
package. Let’s put the two source file obiwancpp.cpp
and obiwanpy.py
.
#! /usr/bin/env python import rospy rospy.init_node("Obiwan") rate = rospy.Rate(2) while not rospy.is_shutdown(): print "Help me Obi-Wan Kenobi, you're my only hope" rate.sleep()
#include <ros/ros.h> int main(int argc, char** argv) { ros::init(argc,argv,"ObiWan"); ros::NodeHandle nh; ros::Rate loop_rate(2); while(ros::ok()) { ROS_INFO("Help me Obi-Wan Kenobi, you'are my only hope"); } return 0; }
2.3 Type the following command to compile the package
cd ~/catkin_ws catkin_make source devel/setup.bash
2.4 After compile, let’s try to run the python script first
rosrun obiwan obiwanpy.py
You should see the output. The script executed without any problem.
2.5 Now try to run the C++ file in the same way. I bet it didn’t run! It turns out, to use the C++ file, you have to uncomment the following part in CMakeLists.txt
.
add_executable(obiwancpp src/obiwan.cpp) add_dependencies(obiwancpp ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(obiwancpp ${catkin_LIBRARIES} )
Then compile and run again. You’ll see the output now.
Step 3: Master the Concept – Python vs C++ in ROS
The main difference between using C++ and Python in ROS is that you have to write down comments every time to include all the source files in CMakeLists.txt
to compile and generate the executable.
QED 🙂
Extras: Video
Here is a sights and sounds version of the post, in case you prefer to see the action that way!
Further learning
If you are a ROS beginner and would like to learn more about programming ROS, please check one of the courses below, depending on which programming language you’re more familiar with:
- ROS Basics in 5 Days (Python)
- ROS Basic in 5 Days (C++)
Feedback
Did you like this post? Please leave a comment on the comments section below, so we can interact and learn from each other. Thank you!