linux下使用vscode对C++项目进行编译

项目的目录结构

linux下使用vscode对C++项目进行编译_第1张图片

头文件swap.h

在自定义的头文件中写函数的声明。

// 函数的声明
void swap(int a,int b);

swap.cpp

导入函数的声明,写函数的定义

#include "swap.h" // 双引号表示自定义的头文件
#include 
using namespace std;

// 函数的定义
void swap(int a,int b)
{
    int temp=a;
    a = b;
    b = temp;
    cout <<"a="<<a<<endl;
    cout <<"b="<<b<<endl;
}

main.cpp

主函数

#include 

using namespace std;
#include 
// 函数的分文件编写

// // 函数的声明
// void swap(int a,int b);

// // 函数的定义
// void swap(int a,int b)
// {
//     int temp=a;
//     a = b;
//     b = temp;
//     cout <<"a="<
//     cout <<"b="<
// }

int main()
{
    int a=10;
    int b=20;
    swap(a,b);
    return 0;
}

编译

按ctrl+` 打开终端
输入以下命令进行编译

g++ main.cpp src/swap.cpp -Iinclude -o main

-I是指定头文件所在的目录,include此处是头文件swap.h放置的目录。
g++后面是要编译的文件,main和src目录下的文件都要编译。

运行

终端中输入以下命令

./main

你可能感兴趣的:(C++笔记,linux,vscode,c++)