Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, how can I make typedefs visible to every file in my project?

I have a typedef

 typedef unsigned int my_type;

used in a file. I would like to make it visible across all my files, without putting it in a header file included by everything. I don't want to go the header file route because as it stands this will be the only declaration in the header file (and it seems unnecessary to add a file just for this).

Is there a way to do this?

If instead I had:

typedef X my_type;

where X was a class, would I need to include X.h everywhere and have the typedef at the end of X.h ?

like image 749
user231536 Avatar asked Apr 19 '10 14:04

user231536


3 Answers

I don't want to go the header file route because as it stands this will be the only declaration in the header file (and it seems unnecessary to add a file just for this).
What's the problem with that? It seems just as unnecessary to avoid creating a file at all costs.

Is there a way to do this?
Not as far as I am aware.

would I need to include X.h everywhere and have the typedef at the end of X.h ?
No, but that's probably the best thing. The only reason you should be doing that is if X is a template, and you need templates to be in headers anyway.

like image 122
Billy ONeal Avatar answered Oct 09 '22 02:10

Billy ONeal


No way around this as far as I can see. Why don't you make a globals.h header file with just the declarations you want everywhere and include that?

Don't be tempted to bury your typedef somewhere and hope that 'since everything else hangs off the header' that it'll be as good as adding a global header - it is extremely bad practice to have headers that are not self contained.

Also, to prevent cluttering up the global namespace create your own:

namespace MyTypes
{
    typedef A B;
    const unsigned int g_nMyGlobalType = 10;
    // etc.
}

That way you can use your globals in a nice uncluttered way:

MyTypes::B myVar; // etc
like image 10
Konrad Avatar answered Oct 09 '22 02:10

Konrad


I would use the header file route, it's not so bad.

No you wouldn't need to include X.h everywhere, just in the places where you use the typedef.

like image 1
demoncodemonkey Avatar answered Oct 09 '22 00:10

demoncodemonkey