繁体   English   中英

Makefile链接问题与堆叠类

[英]Makefile linking issue with stacked classes

我试图为一段代码编写一个makefile,该代码实现依赖于其他类的多个类。 为了执行此操作,我认为我可以使用目标文件隔离代码,然后将所有内容编译为可执行文件,但我始终遇到相同的错误:

ld: symbol(s) not found for architecture x86_64

clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

我已经进行了一些测试以试图找出问题所在,但最终我还是很沮丧。 我的代码分为三个源代码文件,两个头文件和一个makefile。

这是B类的声明:

#ifndef B_H
#define B_H

class B
{
private:
    int _b;

public:
    B(int b);
    ~B();

    int getB();
};

#endif

这是B类的源代码:

#include "b.h"

B::B(int b)
{
    _b = b;
}

B::~B()
{

}

int B::getB()
{
    return _b;
}

这是C类的声明:

#ifndef C_H
#define C_H

#include "b.h"

class C
{
private:
    int _a;
    B* _b;

public:
    C(int a, int b);
    ~C();

    int add();
};

#endif

这是C类的源代码:

#include "c.h"
#include "b.h"

C::C(int a, int b)
{
    _a = a;
    _b = new B(b);
}

C::~C()
{
    delete _b;
}

int C::add()
{
    return _a + _b->getB();
}

这是可执行文件的源代码:

#include "c.h"
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    C adder = C(3, 5);
    cout << adder.add() << endl;
}

这是makefile:

OPTS = -Wall

test: test.cpp c.o
    g++ -o test test.cpp c.o

c.o: c.cpp c.h b.o
    g++ -c c.cpp b.o

b.o: b.cpp b.h
    g++ -c b.cpp

这是输出:

g++ -c b.cpp
g++ -c c.cpp b.o
clang: warning: b.o: 'linker' input unused
g++ -o test test.cpp c.o
Undefined symbols for architecture x86_64:
  "B::getB()", referenced from:
      C::add() in c.o
  "B::B(int)", referenced from:
      C::C(int, int) in c.o
  "B::~B()", referenced from:
      C::~C() in c.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [test] Error 1

代码在执行时应将int值3和5传递给类C,然后将其输出8。然后,将值5和5传递给类B。然后从类B访问值5,并将其与类C中的私有变量求和,然后发送到标准输出。

使用以下命令时,文件可以正常编译,这使我相信该错误在链接器中:

g++ -o test test.cpp c.cpp b.cpp

如果您有任何建议,我将很高兴听到他们的建议。 谢谢

您的问题在这里:

g++ -c c.cpp b.o
clang: warning: b.o: 'linker' input unused

当您使用-c ,编译器将不会链接,只需将源文件编译为相应的目标文件即可。

解决方法是在此处更新您的makefile行:

test: test.cpp c.o b.o
    g++ -o test test.cpp c.o b.o

换句话说,将目标文件bo添加到这两行。

然后从此处删除相同的内容(并将bh添加为依赖项)

c.o: c.cpp c.h b.h
    g++ -c c.cpp

暂无
暂无

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

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