编译单独的.h和.cpp文件时出现链接器错误

问题描述 投票:0回答:1

编译此文件的正确方法是什么?演示该问题的最小代码:

//main.cpp
#include "header.h"
#include <iostream>

using namespace std;
int main()
{
    auto z = myNameSpace::Complex(1, 2);
    cout << z << endl;
    return 0;
}
////////////////////////////////////////
//header.h
#pragma once
#include <iostream>
namespace myNameSpace
{
class Complex
{
public:
    int x;
    int y;

    Complex(int x, int y);
    friend std::ostream &operator<<(std::ostream &os, const Complex &a);
};
}
///////////////////////////////////
//header.cpp
#include "header.h"
using myNameSpace::Complex;
Complex::Complex(int x, int y) : x(x), y(y){};
std::ostream &operator<<(std::ostream &os, const Complex &a)
{
    os << a.x << "+i" << a.y;
    return os;
}

我想使用make来编译单独的对象并将它们链接起来,我缺少了什么?这是我的make命令的输出]

$ make
g++    -c -o main.o main.cpp
g++    -c -o header.o header.cpp
g++ -o main.exe main.o header.o
main.o:main.cpp:(.text+0x33): undefined reference to `myNameSpace::operator<<(std::ostream&, myNameSpace::Complex const&)'
collect2.exe: error: ld returned 1 exit status
make: *** [makefile:2: main.exe] Error 1

这是我的make文件

main.exe: main.o header.o
    g++ -o main.exe main.o header.o

header.o: header.cpp header.h

main.o: main.cpp

.PHONY: clean
clean:
    rm *.o
c++ makefile
1个回答
0
投票

我会这样写header.cpp

///////////////////////////////////
//header.cpp
#include "header.h"
namespace myNameSpace {

Complex::Complex(int x, int y) : x(x), y(y){}

std::ostream &operator<<(std::ostream &os, const Complex &a)
{
    os << a.x << "+i" << a.y;
    return os;
}

}
© www.soinside.com 2019 - 2024. All rights reserved.