体系结构x86_64的未定义符号:链接器错误

Undefined symbols for architecture x86_64: linker error

本文关键字:链接 错误 符号 未定义 x86 体系结构      更新时间:2023-10-16

我正在尝试对 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)

您应该在链接C++程序时指定所有翻译单元文件。

您的程序由两个源文件组成,testMain.cppfunctions.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 有助于自动化此操作。