Problem with Header files

Started by
2 comments, last by CzarKirk 13 years, 4 months ago
Hi all,
im having a problem using header files with c++ ( Visual Studio 2010 )

In the header file stdafx.h i include the structs :


struct player_info{

int x;
int y;
int character;
int mob_range[10];
int target;

};

struct mob_info{
int x;
int y;
float hp;
};


struct PlayerPosPacket {

int movement; // 1:up 2:down 3:left 4:right
player_info ary[10];
mob_info ary_mobs[10];
int id_client;
float damage;
int clientfail;
};


Then i declare :


PlayerPosPacket packet;

In the main.cpp file i call in main() for example:

packet.damage;

But the compiler gives me this error :

error LNK2005: "struct PlayerPosPacket packet" (?packt@@3UPlayerPosPacke@@A) already defined in stdafx.obj


What can be the problem ?
Advertisement
Read this.

In a nutshell, you define "packet" in a header file that ends up making it included in main.obj and stdafx.obj. stdafx.h is for precompiled headers in Visual C++ and I never used them so I don't know what the normal behavior is. As the above link explains doing this is incorrect in C and C++.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

stdafx.h is a special file, called a precompiled header. These are usually used to group all your external includes. The compiler processes them once and can quickly load them afterwards, reducing build times. Putting your own types or includes in it can lead to problems, and can negatively affect build times because this header will need to be reprecompiled every time you change something.

Put the structures in a separate header, and don't include it in stdafx.h, include it directly in the headers or source files that require it.

This isn't the cause of your problem, but it is worth mentioning IMO.
For each structure or related group of structures, put their definitions in a header file along with prototypes for functions that use them. Then in a cpp file of the same name, implement the functions. For example, player.h for player_info and prototypes void move_player(player_info *player, int dx, int dy) etc, then in player.cpp put the code for that function. Put mobs in their own pair of files. That way you build up a well organised program.

As mentioned, precompiled headers are not for regular code, they are for things that are already complete and finished, such as the standard libraries.

This topic is closed to new replies.

Advertisement