When I compile the program I am working on I get:
expected initializer before 'class'
error in my Class.h file. I looked up the error message on the internet, but couldn't find the exact error, although similar errors seem to be caused by missing semicolons but I don't see why I need one. This is the code the error points to, I have no other functions or classes before it.
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
In the Class.cpp file the double dAccountChange(double dChange) function is defined. I don't think this is where the error is coming from but this is the code;
double Account::dAccountChange(double dChange)
{
dAccountBalance += dChange;
return 0.0;
}
When I change the code in Class.h to look like this,
;
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
it doesn't generate an error message, but I can't work out why I need the semicolon before it as the only code I have before it are the following pre-processor lines.
#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED
Any ideas on why the error is generated?
Most likely, in the header file you include immediately before class.h, you'll have something like:
class xyzzy {
int plugh;
}
without the closing semi-colon. That will make your code sequence:
class xyzzy {
int plugh;
}
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
which is clearly invalid. Inserting a semi-colon in class.h before the first line will fix it, but it's clearly the wrong place to put it (since it means every header file you include immediately after that one would need a starting semicolon - also, it's part of the definition in the first header and should be there).
Now that may not be the exact code sequence but it will be something very similar, and the underlying reason will be a missing piece of text in the previous header.
You should go back and put it in the earlier include file.
For example, consider:
include1.h:
class xyzzy {
int plugh;
}
include2.h:
class twisty {
int little_passages;
};
main.cpp:
#include "include1.h"
#include "include2.h"
int main (void) {
return 0;
}
Compiling this produces:
include2.h:3: error: multiple types in one declaration
but placing the semicolon at the end of include1.h (or start of include2.h though we've already established that's not a good idea) will fix it.
The problem is in one of the other headers, one that you #include ahead of class.h.
If you show us the top of your main cpp file, it might give a clue.
Related
I've combed through Google and Stack Overflow looking for an answer to this problem. I know this is super basic, and I'm really irritated I can't figure out what is wrong. So my graduate professor wants us to make an implementation of a Queue for integers. Why? Because this is "Principles of Programming" and we're basically going over ever single little detail with super concise definitions. It's honestly the biggest waste of a three hour class I've ever had to take, but at least the teacher is good. Anyways, I've got the class definition in a .h file, which contains
#ifndef QUEUE_H
#define QUEUE_H
class Queue
{
private:
std::vector<int> myQueue;
public:
int push(int);
int pop_front();
int size();
bool empty();
};
#endif
So, I feel like Queue::size() and Queue::empty are declared right? Well, in my queue.cpp file, I've got the details of these functions...
#include <vector>
#include "queue.h"
int Queue::push(int intToPush)
{
myQueue.push_back(intToPush);
return 0;
};
int Queue::pop_front()
{
int front = myQueue.front();
myQueue.erase(myQueue.begin());
return front;
};
/*
int Queue::size(); <- It was these semicolons
{
return myQueue.size();
};
bool Queue::empty(); <- This one too.
{
return myQueue.empty();
};*/
And when I compile it like this, it does fine, but when I include those two that I have commented out, it gives the error I put in the title of this post.
I'm really sorry that this is so basic and stupid, but I can't find anything to help me and it really perplexes me that these functions are causing the compiler to say that their being declared outside of the class. I tried using the generic returns, 0 and false, and get the same compilation error.
Remove the semicolon from the end of the function names in the cpp file and try compiling again. You can also remove the semicolons trailing the terminating brackets of all of the function definitions. They are not necessary.
This question already has answers here:
error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere
(9 answers)
Closed 7 years ago.
You could have forgot to include problemclass.h from the file where you are using ProblemClass.
You could have misspelled the name of ProblemClass either in its own header file or in the place where you are using it. This can be
hard to spot if it is a capitalization error such as writing
Problemclass or problemClass instead of ProblemClass.
You could have copy-pasted your inclusion guard #defines from one header file to another and then forgot to change the defined names.
Then only the first of those two included header files would take
effect.
You could have placed ProblemClass in a namespace A, in which case you must refer to ProblemClass as A::ProblemClass if you are referring
to it from outside the namespace A.
You may be using templates and not expecting two-phase lookup to work the way it does.
You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old
version of that file under the misspelled name.
You could have made ProblemClass a macro that only gets defined after you include problemclass.h, in which case what you see as
ProblemClass gets replaced by something else by the macro
preprocessor.
You could have defined ProblemClass in a header file other than problemclass.h and then problemclass.h actually defines something
else.
The above was taken from another similar question, I found the points useful but none actually solved my problem, stated hereunder:
I'm creating a natural language processor for a robot, giving the software various objects to represent real world items in its environment (Blocks world for now), one of the objects defined in Block:
/*
* Block.h
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#ifndef BLOCK_HPP_
#define BLOCK_HPP_
#include "typedefinitions.h"
#include "dynamixel.h"
#include "BasicRobotFunctions.hpp"
class Block {
public:
bool grounded;
//TODO position is a deprecated variable, replace with distance from
//pos position;
int number;
int distance;
int object_brightness;
Block(BasicRobotFunctions basic);
virtual ~Block();
void setBrightness(int brightness);
void setGrounded(bool ground);
//void setPosition(int x, int y);
void setDistance(int number);
void setNumber(int number);
//pos getPosition();
int getNumber();
int getDistance();
bool getGrounded();
int getBrightness();
int lookAround(BasicRobotFunctions basic);
};
#endif /* BLOCK_H_ */
with source file:
/*
* Block.cpp
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#include "Block.hpp"
#define DEFAULT_PORTNUM 3 // COM3
#define DEFAULT_BAUDNUM 1 // 1Mbps
Block::Block(BasicRobotFunctions basic) {
grounded = false;
number = Block::lookAround(basic);
}
Block::~Block() {}
void Block::setGrounded(bool ground){
grounded = ground;
}
/*
void Block::setPosition(int x, int y){
position.x = x;
position.y = y;
}*/
void Block::setDistance(int dist){
distance = dist;
}
void Block::setNumber(int num){
number = num;
}
bool Block::getGrounded(){
return grounded;
}
/*
pos Block::getPosition(){
return position;
}*/
int Block::getNumber(){
return number;
}
int Block::getDistance(){
return distance;
}
int Block::getBrightness(){
return object_brightness;
}
//TODO Arrange function to incorporate Turn() in BasicRobotFunctions
int Block::lookAround(BasicRobotFunctions basic){
int num = 0;
dxl_initialize(DEFAULT_PORTNUM,DEFAULT_BAUDNUM);
for(int i = 0;i<360;i++){
dxl_write_word(11,32,-255);
dxl_write_word(11,30,200);
basic.Step(1);
dxl_write_word(11,32,255);
dxl_write_word(11,30,100);
if(dxl_read_byte(100,32) >= dxl_read_byte(100,52)){
num++;
}
}
dxl_terminate();
return num;
}
void Block::setBrightness(int bright){
object_brightness = bright;
}
I am however receiving the following compilation error from the constructor and from the turnAround(BasicRobotFunctions) method:
In file included from Robot.hpp:11,
from BasicRobotFunctions.hpp:12,
from main.cpp:8:
Block.hpp:23: error: expected `)' before 'basic'
Block.hpp:35: error: 'BasicRobotFunctions' has not been declared
make.exe: *** [main.o] Error 1
Having checked my other classes utilizing objects as variables I get the same error.
In response to the points in the quote:
- BasicRobotFunctions.hpp is included
- the class name is spelt the same in all different instances mentioning it
- I didn't copy paste any inclusion guard
- I didn't use any namespaces in the project
- Nor am I using any templates
- the file name isn't misspelled in my include
- I haven't defined any macros in the program
- I made sure every class was defined in its own header file
Is there any other issue my system could possibly have, any mistake I'm making or simply anything I'm doing which is bad programming practice here?
The cause of your problem:
You have a header file circular dependency problem.
main.cpp includes BasicRobotFunctions.hpp
which includes Robot.hpp
which includes Block.hpp
which includes BasicRobotFunctions.hpp.
If your header files are properly guarded against multiple inclusion (which it seems that they are), Block.hpp won't see the definitions of BasicRobotFunctions.hpp because it is already in the middle of including it.
How to spot the problem:
The source of this problem is apparent in the compilation error message and in your Block.hpp file.
The compiler is reporting an error in Block.hpp, and it is describing line by line how it got to that file via inclusions. The source to your Block.hpp file makes it clear that it is trying to include BasicRobotFunctions.hpp.
The fix:
In your case, you can modify your method signatures in Block.hpp to use a (perhaps constant) reference to the BasicRobotFunctions type, and then forward declare the type. This allows you to eliminate the dependency on the BasicRobotFunctions.hpp header file. (Block.cpp would likely need to include both Block.hpp and BasicRobotFunctions.hpp.)
//...
#include "typedefinitions.h"
#include "dynamixel.h"
class BasicRobotFunctions; // Forward declaration
//...
Block(const BasicRobotFunctions &basic);
//...
int lookAround(const BasicRobotFunctions &basic);
//...
You may be able to avoid this problem in the future by minimizing what headers are required to allow your header file to compile. This means your header file should:
Use forward declarations to types that are used.
Use references to forward declared types.
You can check that your header file has minimized its dependencies by making sure it compiles by itself. I accomplish this by including the header file first in a corresponding source file, and then make sure the source file compiles.
// Foo.cpp
#include "Foo.hpp"
//...
Well you can put a forward declaration before the class as
class BasicRobotFunctions;
class Block {
public:
bool grounded;
//TODO position is a ...
but this kind of error means that the #include "BasicRobotFunctions.hpp"
don't declare the BasicRobotFunctions. It's possible a trouble with code guards?
The circular inclusion can be solved using the forward declaration, putting correct guards in headers and moving some includes to source files.
I have a C++ project in VS with more or less 100 files (each file is a class). I modified one a couple of days ago, adding some declarations, and now I can't compile and it gives a lot of errors and this one lastly:
error count exceeds 100; stopping compilation
Posting the errors seems useless, but here are some (the are all pretty much the same):
error C2275: 'btTransform' : illegal use of this type as an expression
error C2275: 'btVector3' : illegal use of this type as an expression
error C2275: 'btVector3' : illegal use of this type as an expression
error C2275: 'btVector3' : illegal use of this type as an expression
error C2504: 'Platform' : base class undefined
error C2535: 'btAlignedObjectArray<T>
Note than most of the mentioned errors shouldn't be errors, and IntelliSense shows no error in the error list output. And I am completely sure I forgot a ; or something similar.
What should I do? Also I am working with a lot of stuff, and I forgot which file I modified. I browsed through most of them and couldn't find anything.
Here is the complete list: http://pastebin.com/1CD9fGgn (it is so long that it doesn't fit here)
As requested:
Player.h
#pragma once
#include <Ogre.h>
#include "BtOgreGP.h"
#include "BtOgrePG.h"
#include <OISKeyboard.h>
#include <OISJoyStick.h>
#include "BulletCollision\CollisionDispatch\btGhostObject.h"
#include "balance.h"
#include "WorldGenerator.h"
#include "Keys.h"
#include "PlayerController.h"
using namespace Ogre;
class Player
{
public:
Player(Root*, SceneManager*, RenderWindow*);
~Player(void);
Camera* mCamera;
void update(const FrameEvent&);
bool isTouchingBelow();
// bool isJumping();
btPairCachingGhostObject* getGhostObject()
{
return mGhostObject;
}
void clearObjectTouchingNormal()
{
mNormals->clear();
}
void addObjectTouchingNormal(btVector3* vector)
{
mNormals->push_back(*vector);
}
btAlignedObjectArray<btVector3> getObjectTouchingNormal()
{
return *mNormals;
}
private:
btAlignedObjectArray<btVector3>* mNormals;
double mTimeLastJump;
WorldGenerator* mGenerator;
bool mPressJumpLastUpdate;
// btAlignedObjectArray<btVector3> getObjectTouchingNormal();
Vector3 mLastVectorVelocity;
//SceneNode* mCameraHelper;
SceneNode* mMainNode;
SceneNode* mBodyNode;
SceneNode* mCameraPivot;
SceneNode* mCameraYaw;
SceneNode* mCameraPitch;
SceneNode* mCameraHolder;
SceneManager* mSceneManager;
BtOgre::DebugDrawer* mDebugDrawer;
//btRigidBody* mPlayerBody;
btQuaternion* mDefaultQuaternion;
Vector3 mStartPosition;
PlayerController* mKinematicController;
btPairCachingGhostObject* mGhostObject;
//bool mIsJumping;
Radian mLastRotation;
btVector3 mBodyDimensions;
/*bool mCameraCenterMovementFlag;
Radian mCameraCenterYaw;*/
};
class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback
{
protected:
btRigidBody* mMe;
public:
ClosestNotMe (btRigidBody* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
{
mMe = me;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
{
if (rayResult.m_collisionObject == mMe)
return 1.0;
return btCollisionWorld::ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);
}
};
Globals.h
#pragma once
#include <Ogre.h>
#include <vector>
#include "Player.h"
enum GameDifficulty
{
GD_EASY,
GD_NORMAL,
GD_HARD
};
class GlobalVariables
{
public:
static std::vector<Player*> players;
};
Scroll to the top of your error list, and deal with that one. If you're in Visual Studio, you can compile it and hit Ctrl-Shift-F12.
If you make some error in syntax (my usual one is an unmatched quote or brace), the compiler can lose its context, so everything from that point forward becomes unintelligible to it. The only way you'll get through it is to correct the first error found; and then--if there are still errors--the next one. At some point, you'll find that thing you did, and the rest of the errors will magically disappear.
Welcome to the wonderful world of c++ errors.
When faced with something like this start at the first error reported (Look at the output from the compiler). Then recompile. Repeat until there are no more errors.
There are a lot of different syntax errors that completely muck up the rest of the file. These include bad type in a declaration, missing semi-colon, and missing braces.
I've seen over 200 errors disappear with a one character fix.
Also, if you forget a semi-colon or brace in one header file, it might cause errors in the next included header. I've had really bad errors in windows.h, because I've included my header before it and forgotten something.
Solving tricky compiler error problems like the one you describe become much easier when you dump the (annotated) preprocessed output and look at the information that the compiler is getting. cl.exe takes the /E argument in order to dump the preprocessed output to stdout (see also this SO answer). If you use that, and look at the error in that context, it should be clear.
An error like 'Player': undeclared identifier showing up in the file where you think you're defining that very identifier is likely caused by a circular dependency. For example, does PlayerController.h contain references to the Player class without a forward declaration?
Source control is key. Based on your comment and extra code, please also post player.h contents.
In general in such a horrible case I do binary search with commenting out large portions of the project.
An error in an h file included in several cpps is usually more likely to crate lots of errors from one little mistake. A cpp parsing issue only affects the cpp. Look for an error in an h file.
Also general word of advice, try to keep all the h file references in the cpp files and limit the references made to h files from h files to an absolute minimum, this will reduce include nightmares. As you can see player.h includes a large amount of h files. Each one of them could be the culprit, I suggest commenting them one by one and wait for an error about an undefined symbol instead of the errors you see now. This will mean that you no longer have a parsing error and now have a missing definition (thus the error is in the file you commented out or in one of the files it includes...).
Recently , I was compiling libfacebookcpp on mac os. I found a strange usage which I can't understand.
There are two files, AuthorizedObject.hpp and List.hpp.
At the end of file AuthorizedObject.hpp,there is one line :#include "List.hpp".Now I compile successfully. But
when I move that line to the beginning, error occurs. The skeleton of the codes are:
//AuthorizedObject.hpp
class AuthorizedObject
{
public:
...
template<class TType>
void _GetConnection(const ::std::string& uri, List<TType> *list) const
{
LIBFACEBOOKCPP_CHKARG(list);
Json::Value value;
request_->GetResponse(uri, &value);
list->Deserialize(*this, value);
}
...
}
#include "List.hpp" //end
----------------------------------------------------------
//List.hpp
#include "AuthorizedObject.hpp"
class LIBFACEBOOKCPP_API List : public AuthorizedObject
{
private: // private classes
...
}
I guess if put that line(#include "List.h") at the beginning of AuthorizedObject.hpp, the two files include each other by circle. So the compiler don't know how to compile.But put that line at the end will solve this problem? Why? Thank you in advance.
The difference is in what order classes/functions/... are defined, for example:
#include "one.h"
void foo(bar &);
// Will result into:
class bar {};
void foo(bar&);
Which is valid code. On the other hand:
void foo(bar &);
#include "one.h"
// Will result into statements in different order:
void foo(bar&);
class bar {};
Which means using class bar before it was declared, thus error. You also may need to make sure that no declaration will be processed twice (UmNyobe already covered that partially):
#if !defined( MY_HEADER_INCLUDED_)
# define MY_HEADER_INCLUDED_
// Complete content goes here
#endif /* !defined( MY_HEADER_INCLUDED_) */
This way when you include file for the first time, MY_HEADER_INCLUDED_ won't be defined (contents will be "placed" inside the code). The second time (you will include it in the circle) MY_HEADER_INCLUDED_ will be defined and therefore complete body will be skipped.
You're right, that's the problem. You're wrong that the compiler doesn't know how to compile - it does, you're just using it wrong :).
The include guards at the beginning of AuthorizedObject.hpp (I assume it has include guards or a #pragma once directive) will define AUTHORIZED_OBJECT_H (or similar). After that, you include List.h, which in turn includes the header AuthorizedObject.hpp. Because the include guard macro was already defined, the definition of AuthorizedObject is skipped, so List doesn't know about the type, but is uses it, so you get the error.
If you move the include at the end, the definition of AuthorizedObject was already processed by the compiler, so using it inside List.h is valid.
It's my first code with classes. the dev c++ compiler find 4 errors so i need a help. I think there's something wrong in my concept may be
This was the Header file "complex.h"
class complex{
public:
bool ReadComplex();
private:
double real;
double imag;
};
This is the .cpp file
#include "complex.h"
#include <iostream.h>
#include <math.h>
using namespace std;
bool complex::ReadComplex()
{ cout<<"Enter the real part";
cin>>real;
cout<<"Enter the imaginary part";
cin>>imag;
return true;
}
and i got 4 errors
C:/Dev-Cpp/include/c++/3.4.2/mingw32/bits/c++config.h:57: error: expected unqualified-id before "namespace"
C:/Dev-Cpp/include/c++/3.4.2/mingw32/bits/c++config.h:57: error: expected ,' or;' before "namespace"
C:/Dev-Cpp/include/c++/3.4.2/mingw32/bits/c++config.h:61: error: expected namespace-name before ';' token
C:/Dev-Cpp/include/c++/3.4.2/mingw32/bits/c++config.h:61: error: `' is not a namespace
Thanks a lot,
class definition should end with a ;
class complex
{
// ....
} ;
//^ missing semi-colon
You forgot the semicolon at the end of the class definition:
class complex{
}; //<------- here put a semicolon
Make sure you put the class in your own named namespace, or else not say using namespace std. There's a std::complex type, and although you don't include its header, implementors are allowed to include it themselves in any of the standard headers.
End your class definition with a semicolon: class complex { /* ... */ };
Don't use <iostream.h>. Use <iostream>. Things there are in the std:: namespace, by the way.
What's <Math.h>? Is it some 3rd party library you're using that's installed outside your project tree? If it's your own code or inside your project tree then use double quotes, not angle brackets. Double quotes ask the compiler to search for the code in your tree, whereas angle brackets ask the compiler to look in system directories.
Are you sure the standard math header won't do? Take a look at the <cmath> header.
You should also
make GetReal() and GeatImag() const functions. If the Get or Set counterparts don't do anything special you should throw them away and set the member data public. This because less code is less bugs.
You should take parameters as const references whenever it makes sense. Like in complex::Add(), for example, which should be a const function too if it doesn't change the object.
Your first code with classes should be:
class complex{
};
int main()
{
return(0);
}
Seriously. Get this to work, with no compiler warnings. Then add complexity a little at a time, and never add to code that doesn't work.