HemoGoblin
HemoGoblin

Reputation: 155

Extern unnamed struct object definition

I got a global object of type "unnamed-struct" and i'm trying to define it. I don't want to pollute my global namespace with such useless type (it will be used only once).

Global.h

extern struct {

    int x;

} A;

Is there any correct way to define such object?
I was trying this:

Global.cpp

struct {

    int x;

} A = { 0 };

But VS2012 throws "error C2371: 'A' : redefinition; different basic types". Thanks.

Upvotes: 6

Views: 2284

Answers (3)

Dugan
Dugan

Reputation: 21

I don't know if this helps you, and this my first post... So take it easy.

I just ran into this issue and what I did was I added a function that manipulates the struct to the file that contained the anonymous struct. That way I can call that function from any file in my project, and it manipulates the values in the struct for me.

Here is an example:

header.c has this anonymous struct:

 struct 
   {    
       char  line1[80];
       char  line2[80];
       char  line3[80];
   } header;

I want to manipulate those values in "interface.c" because I am making a command line interface in another file. My first instinct was to use an extern, but it seems like adding the following function to header.c is just as good or better (Some people discourage the use of externs when avoidable).

void changeHeaders(char *one, char *two, char *three);
void changeHeaders(char *one, char *two, char *three)
{

    strcpy(header.line1, one);
    printf("\nHeader 1: %s", header.line1);
    strcpy(header.line2, two);
    printf("\nHeader 2: %s", header.line2);
    strcpy(header.line3, three);
    printf("\nHeader 3: %s", header.line3);

}

Now as long as I include the prototype for that function I can manipulate those struct variables from any file by using that function. Hope that helps someone.

Upvotes: 0

ecatmur
ecatmur

Reputation: 157424

One possible solution: create another file Global_A.cpp that does not include Global.h, and define A there. By the equivalent-definition rule this will be valid, as long as the anonymous struct definitions are equivalent.

This is still a bad idea, and most compilers will warn about it e.g. (gcc): warning: non-local variable `<anonymous struct> A' uses anonymous type.

Upvotes: 2

unkulunkulu
unkulunkulu

Reputation: 11922

There is no way to do just this simply because it would be error prone: some time in the future someone (probably even you) may want to modify this structure's definition and he might forget to do this in the header and source files accordingly. So you will have to invent a name for this structure and use its name the source file and leave its definition up to the header.

Upvotes: 1

Related Questions