Linux下利用shell命令在VSCode中编译C++工程
程序员文章站
2024-02-29 12:36:28
...
首先是测试代码,
包含main函数的
helloworld.cpp
#include<iostream>
#include"print.h"
using namespace std;
int main()
{
//printHello();
cout << "helloworld!" << endl;
WslPrint wsl;
wsl.Myprint();
getchar();
return 0;
}
print类头文件
print.h
#include<iostream>
using namespace std;
class WslPrint
{
public:
void Myprint();
};
print类的cpp文件
print.cpp
#include "print.h"
void WslPrint::Myprint()
{
cout << "Hello VSCode,this is wsl speaking!" << endl;
}
如果直接按上一篇单文件debug的话,会报Myprint函数无法识别,我们需要通过编写Makefile文件使用make指令生成连接文件。
makefile文件如下:
CC = gcc
XX = g++
CFLAGS = -Wall -O -g
TARGET = ./hello
#compile all .c and .cpp to .o
%.o:%c
$(CC) $(CFLAGS) -c $< -o aaa@qq.com
%.o:%.cpp
$(XX) $(CFLAGS) -c $< -o aaa@qq.com
SOURCES = $(wildcard *.c *.cpp)
OBJS = $(patsubst %.c,%.o, $(patsubst %.cpp,%.o,$(SOURCES)))
$(TARGET):$(OBJS)
$(XX) $(OBJS) -o $(TARGET)
chmod a+x $(TARGET)
clean:
rm -rf *.o hello
makefile的作用是将所有依赖项都按顺序生成
而VSCode中launch.json文件的编写如上篇单文件一样
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/hello",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"preLaunchTask": "build",
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "lldb"
},
"windows": {
"MIMode": "gdb"
}
}
]
}
主要的作用是执行工程
而task.json则是launch.json过程中的任务,比如本文中执行shell指令通过makefile进行make编译出.o文件
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"showOutput": "always",
"tasks": [
{
"taskName": "build",
"command": "make",
"isShellCommand": true,
"showOutput": "always",
"args": ["-lopencl"]
}
]
}
需要注意的是我使用的是ubuntu18.0.4版本,网上很多指令的格式发生了变化,按照网上的代码编写会出现错误,有可能与代码中写的版本有关系
于是出现了我自己写的这个挫版本。。。
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "make",
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "shared",
"showReuseMessage": true
},
"options": {
"shell": {
"args": [
"-lopencl"
]
}
},
"args": [
]
}
]
}
基本上就是将一些命令整合归到某一类中去了,然后一个功能的名字做了一些调整
这些都配置完成之后直接按F5就可以了,在launch中会自动执行tasks中的编译过程
下图为运行结果:
下图为VSCode中Terminal的显示,成功的执行了makefile
这样,就可以编译C++工程了,具体编译顺序由makefile来定
下图为打断点调试
上一篇: skiplist分析和应用
下一篇: Linux环境下的C++编译