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

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 :)
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
so it doesn't complain about it being undefined
Or multiply defined.
Dear everybody,

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

Best Regards,
Siti..:)
or
like this:

extern "C" func();
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
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++.
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.