Project structure

Started by
5 comments, last by NotAYakk 17 years, 11 months ago
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.
bi-FreeSoftware
Advertisement
include .h in .cpp

#include texture.h

Kuphryn
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. :)
Orin Tresnjak | Graphics ProgrammerBethesda Game StudiosStandard Disclaimer: My posts represent my opinions and not those of Bethesda/Zenimax, etc.
sorry that was a typo, in my code it is as you say.
bi-FreeSoftware
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.
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.)
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.)

This topic is closed to new replies.

Advertisement