Présentation
La variable se déclare en dehors de la classe juste après la section include
Pour l'utisiser à l'extérieur du fichier on l'appelle en faisant précéder sa déclaraton par extern :
Exemple
Une variable globale se déclare en dehors de la classe (ici GLOB) dans programme1.cpp
#include <stdio.h>
#include <string>
void fonctionexterne();
using namespace std ;
string GLOB("toto");
main ( int argc, char * argv[] )
{
printf ("GLOB : %s\n",GLOB.c_str());
fonctionexterne();
printf ("GLOB : %s\n",GLOB.c_str());
}
Dans programme2.cpp on l'utilise par le mot extern
#include <stdio.h>
#include <string>
using namespace std ;
extern string GLOB;
void fonctionexterne()
{
GLOB="78872";
}
g++ -c -o programme2.o programme2.cpp
g++ -o programme -o programme2.o programme1.cpp
./programme
Affiche
GLOB : toto
GLOB : 78872