C++ 链接相互引用的排序类。转发don';行不通
我有以下两门课: 具有构造函数Foo(Bar*,int,int)的Foo 和调用新Foo的条(this,int,int) 我假设在Bar.h和/或在Foo.h中向前声明Foo可以解决这个问题 (返回的错误是新Foo上的“未定义引用”) 我正在使用Clang进行编译 目前的链接顺序(但两种情况下都会发生相同的错误)是Foo-then-Bar 有没有想过我做错了什么 代码大致如下。很遗憾,我无法显示任何真实的代码片段C++ 链接相互引用的排序类。转发don';行不通,c++,compilation,linker,makefile,C++,Compilation,Linker,Makefile,我有以下两门课: 具有构造函数Foo(Bar*,int,int)的Foo 和调用新Foo的条(this,int,int) 我假设在Bar.h和/或在Foo.h中向前声明Foo可以解决这个问题 (返回的错误是新Foo上的“未定义引用”) 我正在使用Clang进行编译 目前的链接顺序(但两种情况下都会发生相同的错误)是Foo-then-Bar 有没有想过我做错了什么 代码大致如下。很遗憾,我无法显示任何真实的代码片段 #include Bar.h class Bar ; class
#include Bar.h
class Bar ;
class Foo {
public:
Foo(Bar* bar, int arg1, int arg2) ;
void method1() {
I access bar->field here
}
条形码是
#include Foo.h
class Bar {
public:
Bar() {
Cache* cache = new Cache(this, 0, 0) ;
}
它应该是这样的(不包括警卫): foo.h
class Bar;
class Foo {
public:
Foo(Bar*, int, int);
};
class Bar {
public:
Bar();
};
bar.h
class Bar;
class Foo {
public:
Foo(Bar*, int, int);
};
class Bar {
public:
Bar();
};
foo.cc
#include "foo.h"
// Note: no need to include bar.h if we're only storing the pointer
Foo::Foo(Bar*, int, int) { ... }
// Note: the opposite order would also work
#include "bar.h"
#include "foo.h"
Bar::Bar() {
new Foo(this, int, int);
}
bar.cc
#include "foo.h"
// Note: no need to include bar.h if we're only storing the pointer
Foo::Foo(Bar*, int, int) { ... }
// Note: the opposite order would also work
#include "bar.h"
#include "foo.h"
Bar::Bar() {
new Foo(this, int, int);
}
如果你得到“未定义的引用”“从链接器中,您可能使用与您定义的签名不同的签名声明了
Foo::Foo
,或者根本没有定义它,或者没有链接到编译成的对象文件。显示一些代码。您所描述的很简单。我的代码和您的代码之间的区别似乎是在.cc文件中包含头文件而不是在bar.cc中包含头文件的位置。这是否意味着我应该在bar.cc中包含foo.h而不是bar.h?是的。尽可能避免包含来自其他标题的标题。它还可以加快编译速度。