环境搭建
- 安装 C/C++ 插件后,需要配置C++的一些环境 ctrl+shift+P 执行 C/C++: Edit Configurations(UI) 生成 c_cpp_properties.json,主要是要把c++ 标准选为 11, 否则代码里有些新出的语法特性会报错。
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/include"
],
"defines": [],
"cppStandard": "c++11",
"compilerPath": "/usr/bin/gcc",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
项目构建
新建一个 include 目录,放置一些功能函数,然后用根目录下的 main.cpp 来调用他们,这个就是我们这个项目的全部功能了,主要目的是测试和打通 cmake.
我在 rider.h 里声明了一个类 Animal, 在rider.cpp中实现了它的构造函数。
rider.h:
#ifndef RIDER_H
#define RIDER_H
#include <iostream>
class Animal{
public:
Animal(std::string _name, int _age);
~ Animal(){
std::cout << "animal is destructed" << std::endl;
};
void display(){
std::cout << "hello I am " << name << ", i'm " << age << " years old!"<<std::endl;
}
private:
std::string name;
int age;
};
#endif
rider.cpp
#include <iostream>
#include "rider.h"
Animal::Animal(std::string _name, int _age){
name = _name;
age = _age;
};
main.cpp
#include "rider.h"
int main(){
Animal a("yang", 12);
a.display();
return 0;
}
CMakefileLists.txt
// 注意你自己的cmake version
cmake_minimum_required(VERSION 3.13.4)
project(test1)
include_directories("${CMAKE_HOME_DIRECTORY}/include")
add_executable(test1 include/rider.cpp main.cpp)
构建项目
$mkdir build && cd build
$cmake .. && make
$./test1
#output
hello I am yang, i'm 12 years old!
animal is destructed
一个简单的c++ 程序就构建完了