StereoMatching
StereoMatching

Reputation: 5019

What is the use of declare extern variable in .cpp but not header file?

As far as I know, the extern keyword is used for declaring a global variable which need to be use within several files.Usually the extern keyword is defined in the header file and reuse in many .cpp or header files

Yesterday I saw a special(?) usage in our code bases, the author declare an extern variable in .cpp and define the variable in the main.cpp

d.cpp

extern int whatever; //yes, it is declared in .cpp but not .h

main.cpp

#include "d.hpp"

int whatever = 100;

int main()
{
  //do something
}

What are the benefits and drawbacks of declaring an extern variable in .cpp but not .h?Never hear a technique like this before and can't find an example by google.

Upvotes: 1

Views: 2813

Answers (2)

Rakib
Rakib

Reputation: 7625

extern is used to declare a name with external linkage and which will be defined in somewhere else. It does not matter whether it is declared extern in header or .cpp file. AFAIK, there is no particular drawback or benefit in declaring it in a .cpp file. But as others have pointed out, declaration should be in header file, while definition in source file which includes the header. Using extern may introduce subtle bugs that are hard to find.

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

It doesn't make sense. If d.cpp needs this extern variable, then it should get it by including some header file. If for some reason the author of main decides for whatever reason that "whatever" would be better called "int whatsoever", you'll get a hard-to-find linker error. If the author of main changes it to "char whatever;" then whenever d.cpp writes to what it thinks is "extern int whatever;" it will overwrite some memory, leading to possibly very hard to find bugs.

Upvotes: 5

Related Questions