I know this is a really sad question to ask, but please tell me... how and when should I ever use extern?

I recall an example that Narue showed me but even if I read through the definition from MSDN.com as well as other sources, I still can't quite understand the whole "extern" call.

If someone could please provide me with an example, that would be great. I'll keep looking it up and experimenting in the mean time.

-Alex

The extern keyword is used to tell the compiler that a data object is declared in a different *.cpp or *.c file (code unit). Its required for data objects but optional for function declarations. For example, you have two *.cpp files named A.cpp and B.cpp. B.cpp has a global int that needs to be used in A.cpp.

// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp

int foo()
{
     hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line

int main()
{
    foo();
}
commented: Thank you for the clarification. It was never really explained in this way. +1

Thanks. I never really understood that because my projects always consisted of header files and a main .cpp file - never would I have multiple .cpp's together so it's no wonder that I couldn't explore that idea properly.

I'll experiment by getting used to having multiple .cpp files and headers at the same time - thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.