【问题标题】:c++ extern class does not name a typec++ extern 类没有命名类型
【发布时间】:2023-03-14 09:51:01
【问题描述】:

我正在尝试将一个类对象声明为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 中删除#include "c1.h"
  • 我想在 b1.cpp 中声明和使用 c1 类对象。这就是在 b1.h 中包含 c1.h 的原因。
  • 然后移到b1.cppb1.h 不使用来自c1.h 的任何东西。只包含必要的头文件是一个好习惯。

标签: c++ linux compiler-errors compilation


【解决方案1】:

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;放在@987654341中@ 和#include "b1.h"c2.cpp

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多