因为工作原因开始从头学习C++和cmake等的使用。

Linux下编译cpp

下面是一个非常简单的例子,下载了github开源的json库,创建了一个数组,并且在标准输出打印出来。

// main.cpp
#include <iostream>
#include <json.hpp>

using json = nlohmann::json;
using namespace std;

int main (){
    json mJson;
    for (int i=0; i<10; i++){
        mJson["number"].push_back(i);
    }
    cout << mJson.dump() << endl;
}

// 输出: {"number":[0,1,2,3,4,5,6,7,8,9]}

在Linux平台编译

g++ main.cpp -o myProg -I /json.hpp所在目录/
./myProg

多文件编译

// main.cpp
#include <iostream>
#include <Dog.h>

using namespace std;

int main (){
    woof("meow");
}

// Dog.h
#ifndef DOG_H
#define DOG_H

#include <string>

void woof(std::string woof);

#endif

// Dog.cpp
#include <Dog.h>

void woof(std::string woof){
        printf("%s\n", woof.c_str());
    }

// 执行结果
banana@ubuntu:~/vscodeworkdir$ g++ -c main.cpp -I ./
banana@ubuntu:~/vscodeworkdir$ g++ -c Dog.cpp -I ./
banana@ubuntu:~/vscodeworkdir$ g++ main.o Dog.o -o a -I ./
banana@ubuntu:~/vscodeworkdir$ ./a
meow
banana@ubuntu:~/vscodeworkdir$

在VS Code中编译

使用VSCode打开项目文件夹

文件目录树为

│ │ main.cpp
│ │
│ ├─headers
│ │   Dog.h
│ │
│ └─cpps
│     Dog.cpp

需要配置的有tasks.jsonc_cpp_properties.json

// c_cpp_properties.json
// 让 VS Code识别头文件不报错
"includePath": [
    "${workspaceFolder}/headers"
]

// tasks.json
// 添加代码编译
"args": [
    "-g",
    "${workspaceFolder}/cpps/*",
    "-I",
    "${fileDirname}/headers/"
]