鍍金池/ 問答/C++  HTML/ 使用visual studio code 寫C++ 怎么樣才能正確地引用其他文件

使用visual studio code 寫C++ 怎么樣才能正確地引用其他文件的函數(shù)

使用Visual studio code 配置好C++開發(fā)環(huán)境后想在main函數(shù)里引用其他文件的函數(shù),但是在Mac下總是報(bào)Undefined symbols for architecture x86_64:錯(cuò)誤

代碼如下:
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 啟動(dòng)調(diào)試 輸出:

> 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

怎么解決這個(gè)問題呢。另外,如果怎么正常引用第三方的h文件?

回答
編輯回答
悶油瓶

因?yàn)間++不會(huì)正確的編譯其他的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文件,所以會(huì)出現(xiàn)symbols for architecture x86_64錯(cuò)誤
所以正確的做法是:g++ main.cpp a.cpp -o main.out
再執(zhí)行./main.out
就沒問題了,所以現(xiàn)在問題出來了,那么怎么樣才能讓VSCode正確的編譯所有鏈接的CPP文件呢。

2018年7月27日 07:53
編輯回答
陌上花

想要正確鏈接 cpp 文件,需要通過 -L-I 選項(xiàng)指定頭文件和第三方依賴庫

推薦閱讀文章:https://blog.csdn.net/sunshin...

2017年8月23日 11:47