Home > c/c++ > external variables: C vs. C++

external variables: C vs. C++

The situation is the following: We have two source files (main and core) and want to use the same global variable (headvar) in both of them. In C thats plain easy:

head.h

#ifndef __HEAD_H__
#define __HEAD_H__
 
int headvar; /* global var */
 
int core(int);  /* forward declaration */
 
#endif /* __HEAD_H__ */

main.c

#include <stdio .h>
#include "head.h"
 
int main()
{
        printf( "Hello World!\n" );
        printf("headvar: %d\n", headvar);
        printf("core: %d\n", core(23));
 
        return 0;
}
</stdio>

core.c

#include "head.h"
 
int core(int var)
{
    headvar=42;
    int res=0;
    res=var+headvar;
    return res;
}

In C++ this isn’t going to work as the variable is basically declared twice using the mechanisms as seen above. The reasons for that are quiet complex – you can gain more insight here: http://www.hardforum.com. I’ll only talk about the solution here. You have to make sure that there is only one single memory allocation aka instance of the variable. To ensure this you can use the keyword “external” to tell the compiler-suite that the actual definition occurs elsewhere. Using external you basically tell that there is a name refering to a variable of the given type without actual declaration. You can use this external variable in multiple locations as long as there is one single declaration in one location. So here is the sourcecode of above recoded in C++.

head.h

#ifndef __HEAD_H__
#define __HEAD_H__
 
extern int newvar; /* external declaration */
 
int core(int);  /* forward declaration */
 
#endif /* __HEAD_H__ */

main.cpp

#include <iostream>
#include "head.h"
 
int newvar = 1;	/* actual definition */
 
int main()
{
	std::cout < < "Hello World!" << std::endl;
	std::cout << "newvar: " << newvar << std::endl;
	std::cout << "core: " << core(23) << std::endl;
 
    return 0;
}

core.cpp

#include "head.h"
 
int core(int var)
{
    int res=0;
    newvar=42; /* new value for variable defined in main.cpp */
    res=var+newvar;
    return res;
}

This is nothing new for the casual programmer but can be a real pain in the ass when the error has already been made as the error-messages are mostly “slightly” irritating.

Categories: c/c++ Tags:
  1. No comments yet.
  1. No trackbacks yet.