参考链接 基于VSCode和CMake实现C/C++开发 | Linux篇
根据以上视频第七讲的内容把它写在了ros功能包里面 代码结构如下
相关代码如下: Gun.h
#pragma once
#include <iostream>
#include <string>
class Gun
{
public:
Gun(std::string type)
{
this->_bullet_cout = 0;
this->_type = type;
}
void addBullet(int bullet_num);
bool shoot();
private:
int _bullet_cout;
std::string _type;
};
solider.h
#pragma once
#include <iostream>
#include <string>
#include "Gun.h"
class solider
{
public:
solider(std::string name);
~solider();
void addBulletToGun(int num);
void addGun(Gun *ptr_gun);
bool fire();
private:
std::string _name;
Gun *_ptr_gun;
};
Gun.cpp
#include <Gun.h>
using namespace std;
void Gun::addBullet(int bullet_num)
{
this->_bullet_cout += bullet_num;
}
bool Gun::shoot()
{
if (this->_bullet_cout <= 0)
{
cout << "no bullet" << endl;
return false;
}
this->_bullet_cout -=1;
cout<<"sucess"<<endl;
return true;
}
solider.cpp
#include "Gun.h"
#include "solider.h"
void test()
{
solider sanduo("xusanduo");
sanduo.addGun(new Gun("AK47"));
sanduo.addBulletToGun(20);
sanduo.fire();
}
int main(int argc, char **argv)
{
test();
return 0;
}
main.cpp
#include "Gun.h"
#include "solider.h"
void test()
{
solider sanduo("xusanduo");
sanduo.addGun(new Gun("AK47"));
sanduo.addBulletToGun(20);
sanduo.fire();
}
int main(int argc, char **argv)
{
test();
return 0;
}
之后配置src目录下的CMakeLists.txt文件 添加以下内容
include_directories(include)
add_executable(my_c_exe src/main.cpp src/Gun.cpp src/solider.cpp )
add_dependencies(my_c_exe ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(my_c_exe
${catkin_LIBRARIES}
)
之后进行catkin_make 编译成功后 运行
rosrun 7sample my_c_exe
|