我一直在学习 C++,并且一直在使用一些测试代码来调试一个更大项目的各个部分。我正在尝试使用另一个文件中的对象,但尽管包含了适当的头文件,但我仍然收到 undefined reference 错误。我在 Linux 上使用 Eclipse 和 C++ CDT。代码如下所示:
A.cpp
class A {
private:
int i;
int j;
public:
A(int i1, int i2) {
i = i1;
j = i2;
}
int sum() {
return (i+j);
}
};
啊啊
#ifndef A_H_
#define A_H_
class A {
public:
A(int i1, int i2);
int sum();
};
#endif
主要.cpp
#include <iostream>
#include "a.h"
int main() {
A a(1,2); //undefined reference to 'A::A(int,int)'
std::cout << a.sum(); //undefined reference to 'A::sum(void)'
return 0;
}
这是我的语法问题,还是我需要深入研究编译器?
最佳答案
问题是 main.cpp
只看到头文件 a.h
中类的定义,不包含构造函数和成员函数的定义。
在 A.cpp
中定义了这些函数,但默认情况下它们被定义为内联函数。所以 main.cpp 再次看不到它们的定义。
考虑到根据C++标准(3.2一定义规则)
6 There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then
(6.1) — each definition of D shall consist of the same sequence of tokens; and
所以在A.cpp中你应该这样写
#include "a.h"
A::A(int i1, int i2) {
i = i1;
j = i2;
}
int A::sum() {
return (i+j);
}
类定义也应以分号结尾。
关于c++ - Eclipse (C++) 的 undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778341/