Sign in to follow this  
Torkel

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


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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this