首页 > 解决方案 > 出现错误时我该怎么办:架构 x86_64 的未定义符号?

问题描述

问题

我想重载+=类中的运算符Complex,但是当我通过以下方式编译此项目时出现此错误g++ main.cpp complex.cpp -I complex.hpp -o out

Undefined symbols for architecture x86_64:
  "Complex::operator+=(Complex const&)", referenced from:
      _main in main-bee8d4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

项目

项目树

.
├── complex.cpp
├── complex.hpp
└── main.cpp

复杂的.hpp

#ifndef __COMPLEX__
#define __COMPLEX__

class Complex
{
public:
    Complex(double x=0, double y=0):re(x), im(y){};
    double real() const {return re;}
    double imag() const {return im;}
    Complex& operator+=(const Complex& res);
private:
    double re,im;
};
#endif

复杂的.cpp

#include "complex.hpp"

inline Complex& 
Complex::operator+=(const Complex& res)
{
    this->re += res.re;
    this->im += res.re;
    return *this;
};

主文件

#include "complex.hpp"
#include <iostream>

int main()
{
    Complex c1(1, 1);
    Complex c2(3, 4);
    c2 += c1;
    std::cout << "real part:&quot; << c2.real()  << ", "
              << "image part:&quot; << c2.imag() << std::endl;
    
    return 0;
}

克++

$g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

标签: c++operator-overloading

解决方案


推荐阅读