Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Has Not Been Declared

Tags:

c++

I have seen this type of error everywhere and, although I have looked at the answers, none seem to help.

I get the following error with the following piece of code:

error: 'A' has not been declared

B.h:

#include "A.h"
class B{
    public:
         static bool doX(A *a);
};

A.h:

include "B.h"
class A{};

To run off a checklist of things I've already tried: - Names are spelled correctly - A is in A.h - There are no namespaces - No templates - No macros

I have other classes with can find A just fine. The only thing I can think of is that 'static' is causing a problem.

like image 692
aoi Avatar asked Dec 29 '12 18:12

aoi


People also ask

How do I fix error not declared in this scope?

To resolve this error, a first method that is helpful would be declaring the function prototype before the main() method. So, we have used the function prototype before the main method in the updated code. When we have compiled the code, it throws no exceptions and runs properly.

What has not been declared in this scope?

As from the name we can understand that when the compiler of Arduino IDE is unable to recognize any variable or is unable to process any loop or any instruction having any undeclared variable so it gives the error “not declared in this scope”, which means that code is unable to understand the instruction given in the ...

What does it mean when something is not declared in the scope?

“not declared in this scope” means the variable you referenced isn't defined. The action you should likely take is as follows: You should carefully look at the variable, method or function name you referenced and see if you made a typo.


2 Answers

Replace the include with a forward declaration:

//B.h
class A;
class B{
    public:
         static bool doX(A *a);
};

Include files only when you have to.

Also, use include guards. This will prevent other nasty issues like re-definitions & such.

like image 152
Luchian Grigore Avatar answered Sep 30 '22 17:09

Luchian Grigore


If you have two headers including each other you end up with a circular dependency, and due to the way the preprocessor works it means one will be defined before the other.

To fix, I would avoid including A.h in B.h, and just forward declare instead:

class A;
class B{
    public:
         static bool doX(A *a);
};

You can then include A.h in B.cpp

like image 23
Pubby Avatar answered Sep 30 '22 19:09

Pubby