C++ Crash Course For ROS
C++ Crash Course For ROS
C++ Crash Course For ROS
Justin Huang
Jan 12, 2015
Why C++?
Fast
Compile-time checks
Slight improvement over C
Widely used
Why not?
Complicated
Slow compilation
Hello, world
# include < iostream > public class M ain {
public static void m ain(String[] args) {
int m ain(int argc, char** argv) { System .out.println("H ello, w orld!");
std::cout < < "H ello, w orld!" < < std::endl; }
return 0; }
}
Classes (Java)
public class Robot { Robot r = new Robot("Rosie");
private String nam e;
int m ain() {
Robot r("Rosie");
r.SayN am e();
Robot r2;
r2.SayN am e();
Robot* r3 = new Robot("Rosie");
r3-> SayN am e();
return 0;
}
Vectors
# include < iostream > for(const Robot& robot : robots) {
# include < vector> robot.SayN am e();
# include "robot.h" }
int m ain() { std::cout < < "There are " < < robots.size()
Robot r("Rosie"); < < " robots" < < std::endl;
Robot r2("M osie"); Robot rosie = robots[0];
return 0;
std::vector< Robot> robots; }
robots.push_back(r);
robots.push_back(*r2);
Continued
Hash tables
# include < iostream > robots["Rosie"].SayN am e();
# include < unordered_m ap> return 0;
}
int m ain() {
Robot r("Rosie");
Robot r2("M osie");
Continued
Namespaces
// robot.h // m ain.cpp
# ifndef RO BO T_H _
# define RO BO T_H _ nam espace m yproject {
void inside() {
nam espace m yproject { Robot r;
class Robot { r.SayN am e();
... }
}; };
};
int m ain() {
# endif m yproject::Robot r;
r.SayN am e();
m yproject::inside();
}
using-directive
# include < iostream > # include < iostream >
# include < string> # include < string>
cp ~/samples/subscriber.cpp src
vim src/subscriber.cpp
Or nano src/subscriber.cpp
Or emacs src/subscriber.cpp
Tasks
1. Change the node's name to be your UW NetID
2. Subscribe to "random_numbers" instead of "chatter"
3. Add #include "std_msgs/Float64.h"
4. Change chatterCallback to be:
void chatterCallback(const std_m sgs::Float64& m sg)
5. Change ROS_INFO to say:
RO S_IN FO ("Iheard: % f", m sg.data);
CMakeLists.txt
vim/nano/emacs CMakeLists.txt
Go to near the bottom, where it says
###########
# # BU ILD # #
###########