what is the function of "extern" in C++

Mar 24, 2010 at 2:03am
Dear all,

I have problem to understand what is the function of 'extern' and how to use it..?..Hope you all will explain to me about this function and give some examples..

Your help and attention is much appreciated. Thank you so much..

Best Regards,
as :)
Mar 24, 2010 at 6:09am
extern tells the compiler that the variable is defined somewhere else, so it doesn't complain about it being undefined.

--includes.h
extern int count;

--main.cpp
#include "includes.h"
int count = 4;

--other.cpp
#include "includes.h"
cout<<count; // will output 4

That's the general idea, anyway
Mar 24, 2010 at 7:15am
so it doesn't complain about it being undefined
Or multiply defined.
Apr 5, 2010 at 1:26am
Dear everybody,

Your information, help and attention is much appreciated..:)..Thanks a lot..:D

Best Regards,
Siti..:)
Apr 7, 2010 at 5:40am
or
like this:

extern "C" func();
Apr 7, 2010 at 9:14am
If you use extern keyword it means the variable is declared and it also means that the variable is defined somewhere in the source code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

test.c

#include<stdio.h>
extern int var;
extern int foo();

void main()
{
  printf("value of var from foo: %d\n", foo());
  printf("accessing var directly:%d\n ", var);
}

test1.c

int var; /*global to this file and can be extern-ed by another file*/

int foo(void)
{
   return ++var; 
}

Compiling:
gcc -o test test.c test1.c
Output:
~/test $ ./test
value of var from foo: 1
accessing var directly:1
Apr 7, 2010 at 3:55pm
In the case of extern "C", it specifies that the identifier does/will have C linkage. In other words, it is used to suppress C++ name mangling, which enables a C++ function to be called from C or, the other way around, a C function to be called in C++.
Apr 7, 2010 at 6:31pm
dont forget to put extern "C" inside #ifdef __cplusplus, otherwise c code will give error. it will not understand extern "C".
Topic archived. No new replies allowed.