c ++ extern类没有命名类型

问题描述 投票:-1回答:1

我正在尝试将类对象声明为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时,我无法理解为什么编译器会抱怨b1.h。有人可以帮助解决这个问题吗?

c++ linux compiler-errors compilation
1个回答
2
投票

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

obj_b1class c1没有任何关系,所以从extern b1 obj_b1;删除c1.h

现在c1.h不依赖于b1.h中的任何东西,所以你可以从#include "b1.h"中移除c1.h。出于类似的原因,你应该从#include "c2.h"中删除b1.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

© www.soinside.com 2019 - 2024. All rights reserved.