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
// other includes here
...
extern int hours; // this is declared globally in B.cpp
int foo()
{
hours = 1;
}
// B.cpp
#include
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line
int main()
{
foo();
}
No comments:
Post a Comment