• Advertisement
Sign in to follow this  

Global objects in multi-file projects?

This topic is 4473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement