C++ extern 类没有命名类型

标签 c++ linux compiler-errors compilation

我试图将类对象声明为 extern 但收到以下错误:

g++ a1.cpp -std=c++11

In file included from b1.h:5:0,
                 from a1.cpp:2:
c1.h:6:8: error: ‘b1’ does not name a type
 extern b1 obj_b1;
        ^

我看过了 Issue declaring extern class object'[Class name]' does not name a type in C++

我想我正在按照那里提到的步骤进行操作。但找不到问题所在。

文件是:

a1.cpp

#include<iostream>
#include "b1.h"

b1 obj_b1;


int main(){

    //access object from class B
    std::cout << " test  " << std::endl;
    std::cout << " obj_b1 value is   " << obj_b1.value << std::endl;
    obj_b1.value = 6;
    return 0;
}

b1.h

#ifndef CLASS_B1
#define CLASS_B1

#include "c1.h"

class b1{
public:
    int value=5;
    int print_value();
};
#endif

b1.cpp

#include <iostream>
#include "b1.h"

int b1::print_value(){
        std::cout << "value in b1 is " << value << std::endl;
}

c1.h

#ifndef CLASS_C1
#define CLASS_C1
#include "b1.h" // this is an attempt to fix issue, but didnt work

extern b1 obj_b1; // Is there a better place to declare this ?

class c1 {
private: 
    int c1_value=10;
    int c1_print_value();
};
#endif

c1.cpp

#include<iostream>
#include "c1.h"

int c1::c1_print_value()
{
    std::cout << "in c1 , value is " << c1_value << std::endl;
    std::cout << " obj_b1.value is " << obj_b1.value << std::endl;
    return 0;
}

当我在 extern 声明上方添加 b1.h 时,我无法理解为什么编译器会提示 b1 。有人可以帮忙解决这个问题吗?

最佳答案

b1.h 包含 c1.hc1.h 包含 b1.h。这是一团糟。通过使用#indef/#define组合,你已经防止了无限递归,但它仍然是一团糟。

obj_b1class c1 没有任何关系,因此从 c1.h 中删除 extern b1 obj_b1;

现在,c1.h 不依赖于 b1.h 中的任何内容,因此您可以从 c1.h 中删除 #include "b1.h"。 出于类似的原因,您应该从 b1.h 中删除 #include "c2.h"

另一方面,c2.cpp确实依赖于obj_b1(假设obj1.name是一个拼写错误,应该是obj_b1.name),因此您应该将extern b1 obj_b1;放在b1.h中,并将#include "b1.h"放在c2.cpp中.

要进行一些额外的清理,请将 b1 obj_b1;a1.cpp 移动到 b1.cpp

关于C++ extern 类没有命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52195795/

相关文章:

c++ - 使用不同文件声明函数/vector 的 C++ 中的多重定义错误

c++ - 有没有一种方法可以通过 #define 列出在 c/c++ 中定义的符号

php - 服务器上永远运行的进程

android - 找出给定 IPv4/IPv6 地址的域(不是 rDNS/PTR)

c++ - 在 Linux 中为 c++ 使用 gprof -f 选项

java - "Non-static method cannot be referenced from a static context"错误

c++ - 当小部件太大时的 Gtk 3

c++ - 以最有效的方式合并 C++ vector 或类似数据结构中的某些元素

c++ - 在 C++ 中使用 Lua

c++ - CMake在编译使用OpenCV的项目时遇到问题