架构 i386 的未定义符号:

2021-12-28 00:00:00 macos terminal g++ linker c++

我最近转移到了 mac,并且正在努力使用命令行编译器.我正在使用 g++ 进行编译,这可以很好地构建单个源文件.如果我尝试添加自定义头文件,当我尝试使用 g++ 进行编译时,我会得到架构 i386 的未定义符号.然而,这些程序在 xCode 中编译得很好.我是否遗漏了一些明显的东西?

I've recently moved over to a mac, and am struggling using the command line compilers. I'm using g++ to compile, and this builds a single source file fine. if I try to add a custom header file, when I try to compile using g++ I get undefined symbols for architecture i386. The programs compile fine in xCode however. Am I missing something obvious?

尝试使用 g++ -m32 main.cpp ... 不知道还能尝试什么.

tried using g++ -m32 main.cpp... didn't know what else to try.

好的,旧代码编译...已经缩小到我的构造函数.

Okay, The old code compiled... Have narrowed it down to my constructors.

class Matrix{
public:
    int a;
    int deter;

    Matrix();
    int det();
};

#include "matrix.h"


Matrix::Matrix(){
    a = 0;
    deter = 0;
}

int Matrix::det(){
    return 0;

}

我的错误是体系结构 x86_64 的未定义符号:"Matrix::Matrix()",引用自:_main 在 ccBWK2wB.old:找不到架构 x86_64 的符号collect2: ld 返回 1 个退出状态

my error is Undefined symbols for architecture x86_64: "Matrix::Matrix()", referenced from: _main in ccBWK2wB.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status

我的主要代码有

#include "matrix.h"
int main(){
    Matrix m;

    return 0;
} 

和平常一样

推荐答案

看起来你有三个文件:

  • matrix.h,一个声明Matrix类的头文件;
  • matrix.cpp,一个实现Matrix方法的源文件;
  • main.cpp,一个定义 main() 并使用 Matrix 类的源文件.
  • matrix.h, a header file that declares the Matrix class;
  • matrix.cpp, a source file that implements Matrix methods;
  • main.cpp, a source file that defines main() and uses the Matrix class.

为了生成包含所有符号的可执行文件,您需要编译两个 .cpp 文件并将它们链接在一起.

In order to produce an executable with all symbols, you need to compile both .cpp files and link them together.

一种简单的方法是在您的 g++clang++ 调用中指定它们.例如:

An easy way to do this is to specify them both in your g++ or clang++ invocation. For instance:

clang++ matrix.cpp main.cpp -o programName

或者,如果您更喜欢使用 g++ ― Apple 已经有一段时间没有更新了,而且在可预见的未来看起来他们不会更新:

or, if you prefer to use g++ ― which Apple haven’t updated in a while, and it looks like they won’t in the foreseeable future:

g++ matrix.cpp main.cpp -o programName

相关文章