我试图为一段代码编写一个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
代码在执行时应将8的int值3和5传递给类C。然后将5传递给类B。然后从类B访问值5,并在发送前将值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
换句话说,将目标文件
b.o
添加到两行。然后从此处删除相同的内容(并添加
b.h
作为依赖项)c.o: c.cpp c.h b.h
g++ -c c.cpp
关于c++ - Makefile链接问题与堆叠类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25835330/