c++ “undefined reference to xxx“, “collect2.exe: error: ld returned 1 exit status“

背景

在学习c++设计模式的Pimpl时,一共编写了三个文件:try.h、try.cpp和test.cpp,其中主函数包含在test.cpp中,并在该文件中调用try.h头文件中自定义的类;try.h中的具体实现细节被封装在try.cpp中。

//try.h
class Line
{
public:
    Line(int x1, int y1, int x2, int y2);
    ~Line();
    void printLine() const;

private:
    class LineImpl;
    LineImpl *_pimpl;
};
//try.cpp
#include<iostream>
#include"try.h"

using namespace std;

class Line::LineImpl
{
public:
    LineImpl(int x1, int y1, int x2, int y2);
    void printLineImpl() const;

private:
    class Point
    {
    public:
        Point(int x=-1, int y=2)
        :_x(x)
        ,_y(y)
        {
            cout << "Point()" << endl;
        }

        void printPoint() const;

    private:
        int _x;
        int _y;
    };

    Point _pt1;
    Point _pt2;
};

void Line::LineImpl::Point::printPoint() const
{
    cout << "x=" << _x << ",y=" << _y << endl;
}

Line::LineImpl::LineImpl(int x1, int y1, int x2, int y2)
:_pt1(x1, y1)
,_pt2(x2, y2)
{
    cout << "LineImpl()" << endl;
}

void Line::LineImpl::printLineImpl() const
{
    _pt1.printPoint();
    _pt2.printPoint();
}

Line::Line(int x1, int y1, int x2, int y2)
:_pimpl(new LineImpl(x1, y1, x2, y2))
{
    cout << "Line()" << endl;
}

Line::~Line()
{
    delete _pimpl;
    cout << "~Line()" << endl;
}

void Line::printLine() const
{
    _pimpl->printLineImpl();
}
//test.cpp
#include"try.h"

int main()
{
    Line ln(-1,-2,-3,-4);
    ln.printLine();
}

此时直接使用vscode的编译运行按钮,会产生以下报错信息:

原因分析

可以看到,由vscode自动产生的编译指令中,只对test.cpp进行了编译,忽略了try.cpp,导致头文件中自定义类的具体实现细节没有被链接到test.cpp中,因此报错显示没有找到这些类的具体定义。

解决方法

为简单起见,我们直接使用g++编译命令对上述两个.cpp源文件进行手动编译,输入如下命令:

g++ .\test.cpp .\try.cpp -o .\test
./test.exe

此时便能得到正确答案:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值