# Global objects in multi-file projects?

## Recommended Posts

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

##### Share on other sites
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;

##### Share on other sites
Option #2 is to use:
static kekeke rofl;

But generally I prefer SiCrane's method

##### Share on other sites
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.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628391
• Total Posts
2982419

• 10
• 9
• 19
• 24
• 11