我正在尝试对cpp文件的基本链接进行测试,我一直在搜索并且在寻找解决方案时遇到很多麻烦。我知道我必须在两个cpp中都包含标头,但是在尝试同时运行这两个时遇到了麻烦。
//testMain.cpp
#include <iostream>
#include <stdio.h>
#include "func.h"
using namespace Temp;
int main()
{
getInfo();
return 0;
}
//func.h
#ifndef FUNC_H
#define FUNC_H
#include <iostream>
#include <stdio.h>
namespace Temp{
int getInfo();
}
#endif
//functions.cpp
#include "func.h"
using namespace std;
int Temp::getInfo()
{
return 5 + 6;
}
//error that I'm getting using VS Code
cd "/Users/jcbwlsn/Downloads/Coding/CPP/Workspace/RPG Project/src/" && g++ testMain.cpp -o testMain && "/Users/jcbwlsn/Downloads/Coding/CPP/Workspace/RPG Project/src/"testMain
Undefined symbols for architecture x86_64:
"Temp::getInfo()", referenced from:
_main in testMain-1f71a1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
答案 0 :(得分:0)
链接 C ++程序时,应该指定所有翻译单元文件。
您的程序包含两个源文件,testMain.cpp
和functions.cpp
。
因此 编译链接 命令应类似于:
g++ testMain.cpp functions.cpp -o testMain
或者,您可以编译每个源代码成单独的文件,然后链接它们到可执行文件中:
g++ -c testMain.cpp -o testMain.o
g++ -c functions.cpp -o functions.o
g++ testMain.o functions.o -o testMain
拥有某种Makefile可以自动执行此操作。