mcjohnalds45
mcjohnalds45

Reputation: 707

error: 'x' does not name a type

When I try to declare an instance of my class 'Game' I receive the compile error "error: 'Game' does not name a type" for main.cpp.

If probably doesn't matter but i'm using codeblocks.

Relevant code from Game.cpp

#include "../include/main.h"

class Game
{
    private:

    public:
};

Relevant code from Main.cpp

#include "../include/main.h"

Game g; //this is the line it is referring to

int main(int argc, char* args[])
{
    return 0;
}

I'm only starting to learn c++ so i probably overlooked something obvious :(

Upvotes: 3

Views: 16345

Answers (3)

tyger
tyger

Reputation: 181

Maybe you can remove the Game class declaration in Game.cpp and try to create another file named "Game.h" under ../inclue/ like:

#ifndef _GAME_H_
#define _GAME_H_

class Game
{
    private:
    public:
};

#endif

and include this Header file in Main.cpp. Then I think the error won't happen:)

Because we usually use .cpp file for class definition and .h file for declaration, then include .h file in Main.cpp.

Upvotes: 0

karthik
karthik

Reputation: 17842

C file or cpp file is a matter of multiple errors occurring is compiled.

The header file for each

 # pragma once 
 Or
 # Ifndef __SOMETHING__ 
 # define __SOMETHING__

 Add the code ...

 # Endif

Upvotes: 0

paulsm4
paulsm4

Reputation: 121699

Include the declaration for "Game" in a header

notepad main.h =>

#ifndef MAIN_H
#define MAIN_H

class Game
{
    private:
      ...
    public:
      ...
};
#endif
// main.h

notepad main.cpp =>

#include "main.h"

Game g; // We should be OK now :)

int 
main(int argc, char* args[])
{
    return 0;
}

gcc -g -Wall -pedantic -I../include -o main main.cpp

Note how you:

1) Define your classes (along with any typedefs, constants, etc) in a header

2) #include the header in any .cpp file that needs those definitions

3) Compile with "-I" to specify the directory (or directories) containing your headers

'Hope that helps

Upvotes: 3

Related Questions