Using classes in multiple object files

Started by
2 comments, last by GameDev.net 24 years, 6 months ago
Here's the standard solution to multiple usage of an h file.
If we had a file called example.h at the top of the file simply put

#ifndef _EXAMPLE_H_
#define _EXAMPLE_H_

All your code

#endif

The tag _EXAMPLE_H_ is just an abstract name but it is useful to make it a name which makes sense, so this is the format I use.

This prevents multiple declarations and allows you to declare classes in the .h file which is the best place to put them for external use.

Advertisement
the use of sentinels/include guards/whatever you call them is customary. however, you can do the work of those three lines with

#pragma once

somewhere in each of your .h files. (i usually put it as the first line after the comment saying what the file is)

Get off my lawn!

With classes, is it possible to declare them in one object file and use them in another? you can do this with individual functions using extern, but how can you do it with classes, since I've found the only way is to put the class in the .h file, but won't that mean I will be declaring it multiple times, and I'll get conflicts when I try to link it?

------------------

I hadn't even heard of this pragma directive, so I'm glad to say I learnt something
However, a warning. Pragma's are compiler specific and there's no guarentee that every compiler will know this directive.
It's probably nothing to worry about but, as you can probably tell, I like having the last word

This topic is closed to new replies.

Advertisement