Global objects in multi-file projects?

Started by
2 comments, last by SiCrane 18 years, 4 months ago
Ok, so what I want to do is this:

/* main.cpp */

#include <iostream>
#include "lol.h"

using namespace std;

int main(/*blah blah*/)
{
     lawl(5);
     cout << rofl.lmao;
}

/* lol.cpp */

#include "lol.h"

void lawl(int lol)
{
     rofl.lmao = lol;
}

/* lol.h */

struct kekeke
{
     int lmao;
}

kekeke rofl;

void lawl(int);

This will compile but not link* as it generates an error about declaring
rofl
twice (since lol.h is included in both lol.cpp and main.cpp). I've tried to check up on this and found some tips on enclosing the globally included header in
#ifndef .. #endif
to make sure that it is only compiled once. This does not seem to help, however. Is there a way to do this, or do I have to use some kind of workaround? *using gcc
Advertisement
To declare a global variable in a header you need to use the extern keyword with the declaration. Ex:
extern kekeke rofl;

Then in one source file, at namespace scope (not inside a function or class) you need to define the variable:
kekeke rofl;

For more details see this article.
Option #2 is to use:
static kekeke rofl;

But generally I prefer SiCrane's method
----Erzengel des Lichtes光の大天使Archangel of LightEverything has a use. You must know that use, and when to properly use the effects.♀≈♂?
That doesn't produce a single instance of the global; it produces a separate instance for each source file that includes the header. That is usually not what you want.

This topic is closed to new replies.

Advertisement