简体   繁体   English

架构 x86_64 的未定义符号:linker 错误

[英]Undefined symbols for architecture x86_64: linker error

I'm trying to do a test of basic linking for cpp files, I've been searching all over and am having a lot of trouble trying to find a solution.我正在尝试对 cpp 文件的基本链接进行测试,我一直在搜索并且在寻找解决方案时遇到了很多麻烦。 I understand that I have to include the header in both cpp's, but I'm having trouble trying to run these two together.我知道我必须在两个 cpp 中都包含 header,但是我在尝试将这两者一起运行时遇到了麻烦。

//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)

You're supposed to specify all translation unit files when linking a C++ program.您应该在链接C++ 程序时指定所有翻译单元文件。

Your program consists of two source files, testMain.cpp and functions.cpp .您的程序包含两个源文件testMain.cppfunctions.cpp

Hence the compile-and-link command should be something like:因此, compile-and-link命令应该类似于:

g++ testMain.cpp functions.cpp -o testMain

Alternatively you can compile each source into separately and then link them into an executable:或者,您可以单独编译每个源,然后将它们链接到可执行文件中:

g++ -c testMain.cpp -o testMain.o
g++ -c functions.cpp -o functions.o
g++ testMain.o functions.o -o testMain

Having some kind of a Makefile helps to automate this.拥有某种 Makefile 有助于自动执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM