Advertisement

Visual C++ and multiple source files

Started by July 31, 2001 01:42 PM
2 comments, last by Outworlder 23 years, 6 months ago
I''d like some advice about how to properly work with multiple files in a project. In my case, I have a main souce file (maptest.cpp). It depends on all other files to be built correctly, so I #include them. For clarity''s sake, I will simplify things. I have three(in this example) other source files Map.cpp, Particle.cpp and Renderer.cpp. Map and Particle needs Renderer. If I put all those files in the project, Visual C++ shows all classes and everything is fine, until I try to compile... all the hell break loose. It tries to compile all the files, but since Map needs Renderer, it can''t compile. The same happens with all others. Even if I #include all files in Maptest.cpp, the errors still occur. If I remove everything but maptest from the project (but still include them) everything works fine, but then I lose the nifty class information. So the question is: how can I properly organize the source files, and the correct way to use #include so that everything compiles correctly? Gaiomard Dragon -===(UDIC)===-
Gaiomard Dragon-===(UDIC)===-
Put all your source files seperate, and #include header files only. One source file can depend on another, you just have to make sure that any variables that the two sources share are extern. Don''t #include them though.
Advertisement
What you need to do is when you do your .h files you need to add
Maptest.h#ifndef TEST_H#define TEST_Hrest of .h file#endif 


This will allow the code to be compiled only once.

Also you need to add at the top of the .h files that include other .h files

extern class (name of class)

This will include the class into the file when it compiles it wont mess up.

I hope this helps you some.

Minerjr
Thanks for the answers, I never expected replies so fast

Let me see if I understood correctly:

// Renderer.h

#ifndef RENDERER_H
#define RENDERER_H
class CRenderer {
//blahblahblah
friend CRenderer* GetRenderer();
};

CRenderer* GetRenderer() {
static CRenderer MainRenderer;
return &MainRenderer
}
#endif

// Map.h

extern class CRenderer;
#include "Renderer.h"

#ifndef MAP_H
#define MAP_H

class CMap {
CRenderer* Renderer;
Map() {
Renderer=GetRenderer();
}
};
#endif

// Maptest.h

extern class CMap;
#include "Renderer.h"
#include "Map.h"


// Maptest.cpp

CMap Map();

// rest of the code



I''m typing everything from memory, but it is based on some of my code. Is that it? And also, is that the correct use of extern?

Gaiomard Dragon
-===(UDIC)===-
Gaiomard Dragon-===(UDIC)===-

This topic is closed to new replies.

Advertisement