使用visual studio code 写C++ 怎么样才能正确地引用其他文件的函数

新手上路,请多包涵

使用Visual studio code 配置好C++开发环境后想在main函数里引用其他文件的函数,但是在Mac下总是报Undefined symbols for architecture x86_64:错误

代码如下:
a.h文件

int func();

a.cpp文件

#include <iostream>
#include "a.h"
using namespace std;
int func(){
    return 0;
}

main.cpp文件

#include <iostream>

#include "a.h"

using namespace std;
int main()
{
    int b = func();
    cout << b << endl;
}

按F5 启动调试 输出:

> Executing task: g++ /Users/stanhu/Desktop/Git/Foundation/CPP_Learn/main.cpp -o /Users/stanhu/Desktop/Git/Foundation/CPP_Learn/main.out -g -Wall -fcolor-diagnostics -std=c++11 <

Undefined symbols for architecture x86_64:
  "func()", referenced from:
      _main in main-d53c96.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
The terminal process terminated with exit code: 1

怎么解决这个问题呢。另外,如果怎么正常引用第三方的h文件?

阅读 15.1k
3 个回答
新手上路,请多包涵

因为g++不会正确的编译其他的CPP文件,你可以看VSCode的命令:
g++ /Users/stanhu/Desktop/Git/Foundation/CPP_Learn/main.cpp -o /Users/stanhu/Desktop/Git/Foundation/CPP_Learn/main.out -g -Wall -fcolor-diagnostics -std=c++11
只编译了main.cpp文件而没有编译a.cpp文件,所以会出现symbols for architecture x86_64错误
所以正确的做法是:g++ main.cpp a.cpp -o main.out
再执行./main.out
就没问题了,所以现在问题出来了,那么怎么样才能让VSCode正确的编译所有链接的CPP文件呢。

新手上路,请多包涵

你的c配置lauch.json文件里面在program里面要加入xx.out

"program": "${workspaceFolder}/${fileBasenameNoExtension}/XXX.out"。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题