Definition of extern in C++

External links.


Definition of extern in C++

The extern specifier is used in variable and function declarations (except class members or function parameters). It specifies external binding and does not technically affect storage duration, but it cannot be used in a definition of an automatic storage duration object, so all extern objects have static or threaded durations.

This is useful when you have global variables and declare their existence in a header so that every source file that includes the header knows about it, but you only need to “set” it once in one of your source files .

Example, Suppose you have 3 files and you will link two files:

vim global.hpp

#ifndef GLOBAL_H
#define GLOBAL_H

// any file that includes this header will be able to use "var_global"
extern float var_global;

void the_func();

#endif

vim global.cpp

#include <iostream>
#include "global.hpp"

void the_func(){
    // print global variable:
    std::cout << var_global << '\n';
}

vim main.cpp

#include "global.hpp"

// it will be defined here
float var_global;

int main(){
    var_global = 9.36f;
    the_func();
}

After compiling the output will be: 9.36, but available for all files.

Another way to use the extern keyword is to compile C++ projects into C, for example.

Suppose you are writing a plugin/extension for a program written C, but you are using C++, so you can change the context of your code to C .

Example:

#include <iostream>

extern "C" {
  namespace terroo {
    class DarthVader{
      public:
        DarthVader(){
          std::cout << "I am your father." << '\n';
        }
        ~DarthVader(){
          std::cout << "Nooooooooo ..." << '\n';
        }
    };
  }
}

int main( int argc , char ** argv ){
  terroo::DarthVader t;
  return 0;
}

If a program is written in C it will work with this code, even using classes, constructors, destructors, namespace,…

That’s all for today, small daily doses that will always keep us in tune with C++!


cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles