Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this extern harmless?

Tags:

c++

c

extern

main.h

extern int array[100];

main.c

#include "main.h"

int array[100] = {0};

int main(void)
{
    /* do_stuff_with_array */ 
}

In the main.c module, the array is defined, and declared. Does the act of also having the extern statement included in the module, cause any problems?

I have always visualized the extern statement as a command to the linker to "look elsewhere for the actual named entity. It's not in here.

What am I missing?

Thanks.

Evil.

like image 533
EvilTeach Avatar asked Mar 25 '09 19:03

EvilTeach


2 Answers

The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.

To avoid exposure of names (variables, functions, ..) outside of a specific object (file), you would have to use static.

like image 129
ypnos Avatar answered Sep 24 '22 10:09

ypnos


yea, it's harmless. In fact, I would say that this is a pretty standard way to do what you want.

As you know, it just means that any .c file that includes main.h will also be able to see array and access it.

like image 29
Evan Teran Avatar answered Sep 24 '22 10:09

Evan Teran