【发布时间】: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.cpp;b1.h不使用来自c1.h的任何东西。只包含必要的头文件是一个好习惯。
标签: c++ linux compiler-errors compilation