Sign in to follow this  
AdamGL

Project structure

Recommended Posts

Ok, so I am trying to structure my code "professionaly", using #ifndef and such to make sure my headers don't repeat. Yet they do, and I get errors.
//MAIN
#include <tga.h>
#include "texture.h"

//code

//tga.h
#ifndef _TGA_LOADER_
#define _TGA_LOADER_

int loadTGA(char *filename) //  <--- lets just say
{
     //stuff
}

#endif

//texture.h
#ifndef _TEXTURE_HANDLER_CLASS_
#define _TEXTURE_HANDLER_CLASS_

class TEXTURE
{
   //stuff
};
#endif

//texture.cpp
#ifndef _TEXTURE_HANDLER_FUNC_
#define _TEXTURE_HANDLER_FUNC_
#include <tga.h>
#include "texture.cpp"

void TEXTURE::something() //  <-- some function from texture.h
{

}
#endif

It says my functions from tga.h are defined twice, but I put guards. I don't know what's going on.

Share this post


Link to post
Share on other sites
Well for starters, you're including a .cpp file in itself. (You should never have to #include a CPP file anyway.) Also, you don't need compilation guards in CPP files. :)

Share this post


Link to post
Share on other sites
The reason why you are getting an error is because you're putting the code inline in the header file and then including that file in two separate translation units(*.cpp files). This means that the code exists twice and the linker doesn't know which on to choose when linking the units together. The solution is either to move the code to a .cpp file and only have a forward declaration of the function in the header file or to put the inline keyword in the function definition.

Share this post


Link to post
Share on other sites
0) Yeah, like they said. No including of .cpp's.
1) Because no including of .cpp's, no need for guards on .cpp's.
2) Did you read this? Try again?
3) Post an *actual* sample that causes the problem and the compiler/linker's complaint.
4) No, really, read it again.

(Edit: jamessharpe is correct, but the above is the process generally recommended for fixing this sort of thing.)

Share this post


Link to post
Share on other sites
First, you should tend to not implement functions in header files.

If you are implementing functions in header files, they should be inline or in an anonymous namespace.

(Heck, the only function implementations that shouldn't be in anonymous namespaces are functions forward-declaired in .h files and implemented in .cpp files, and one or two other rare technical situations.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this