Hi,

After a year of using c# and gaining object programming experience I decided to improve my c++ skills.

What I particularly liked about c# was the way of dividing source into different files. It all just worked fine :).

Now I want to do the same using c++. I'm going to create an sdl game, and to avoid a mess in code, I want to divide it all at least into the following sections: main, load_data, update, draw.

The problem is that functions in all of those sections will use the same data and probably will use the same classes/structures.

1)I tried myself divide the code, but it doesn't work, and below you can see an example, of what I tried:

main.cpp

#include "declarations.h"
#include "load_resources.cpp"

Resources res;

int main ( int argc, char** argv )
{
    load(res);

    return 0;
}

declarations.h

#ifndef DECLARATIONS_H_INCLUDED
#define DECLARATIONS_H_INCLUDED

struct Resources
{
    int a;
    int b;

};

bool load(Resources &res);

#endif // DECLARATIONS_H_INCLUDED

load_resources.cpp

#include "declarations.h"

bool load(Resources &res)
{
    return true;
}

multiple definition of `load(Resources&)'|


2) The other problem is that every section should have access to the same data. What's, the best way for it? In c# I just had to create a public static call. In c++ - I have no idea.

Help me please.
Bye

Never ever for any reason whatsoever include one *.cpp file in another. Even C# does not do that. Each *.cpp file has to be compiled on its own and then all of them linked together at link time. Exactly how to do that will depend on the compiler/IDE that you are using.

As for public data used in multiple *.cpp files: Just add the declaration in the *.h file but use the extern keyword, such as extern Resources res; . That just tells other *.cpp files that the object will be declared publically in some other *.cpp file. Then do NOT change the declaration as you have it in main.cpp because that's the one that actually creates the object.

Similar with function prototypes. Just put them in header files with or without extern keyword, then write the implementation of the function in one of the *.cpp files.

Thanks, you probably saved a few other hours my time. That's exactly what I needed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.