【发布时间】:2014-09-14 16:18:32
【问题描述】:
我正在尝试为一段代码编写一个生成文件,该代码实现依赖于其他类的多个类。为了执行此操作,我想我可以使用目标文件隔离我的代码,然后将所有内容编译成可执行文件,但我一直遇到同样的错误:
ld: symbol(s) not found for architecture x86_64
clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
我已经进行了一些测试以试图找出问题所在,但我最终被难住了。我的代码分为三个源代码文件、两个头文件和一个生成文件。
这是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;
}
这是生成文件:
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 并与 C 类中的私有变量求和在发送到标准输出之前。
使用以下命令时文件编译正常,这使我相信错误出在链接器中:
g++ -o test test.cpp c.cpp b.cpp
如果您有任何建议,我很乐意听到。谢谢
【问题讨论】: