简体   繁体   English

解决 GNU 中的链接器错误以进行重新声明

[英]Resolve linker errors in GNU for redeclaration

I have the following implementation:我有以下实现:

header of A: A的标题:

class A
{
public:
foo();
};

A has its own .cpp file with the implementation for foo() A 有自己的 .cpp 文件,其中包含 foo() 的实现

//header of B //B头

#include "A.h"
class B
{
public foo();
};

Note: B does not have a header of its own注意:B 没有自己的标题

Now in the Class C.cpp, I want to reuse header of A and implementation from Bo So in C.cpp I do:现在在 C.cpp 类中,我想在 C.cpp 中重用 A 的标头和 Bo So 的实现,我这样做:

//C.cpp
#include "A.h"
....
B b;
b.foo();
..

When I compile the above I am bound to get redeclaration error for the function foo().当我编译上面的代码时,我一定会得到函数 foo() 的重新声明错误。 I want to know if there is any way to tell GNU compiler to take Bo and omit Ao.. Or to tell compiler to consider the first object in the make file that contains the implementation and ignore the rest?我想知道是否有任何方法可以告诉 GNU 编译器取 Bo 并省略 Ao .. 或者告诉编译器考虑包含实现的 make 文件中的第一个对象并忽略其余对象?

I am using GNU v2.16我正在使用 GNU v2.16

Your problem is about redeclaration of A since in C.cpp it will see 2 declarations of A one through Ah and other through Bh , so just guard Ah in a header guard to avoid including it more than once, generally you should always guard your headers:你的问题是关于A重新声明,因为在C.cpp它会看到 2 个A声明,一个通过Ah另一个通过Bh ,所以只需在标题保护中保护Ah以避免多次包含它,通常你应该始终保护你的标题:

#ifndef HEADER_A_h_INCLUDED
#define HEADER_A_h_INCLUDED
class A {...};
#endif

Now if you include Ah more than one time this guard will make the second include as nothing!现在,如果您多次包含Ah该守卫将使第二次包含成为空!

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

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