Jaeya Jaeya - 2 months ago 12
C++ Question

Multiple definitions and undefined references

My C++ code gets many "multiple definition" errors when compiled. A minimal example for my situation is:

//testA.h
#ifndef __FILEA_H_INCLUDED__
#define __FILEA_H_INCLUDED__

int A;
int B;

#endif

//testB.h
#ifndef __FILEB_H_INCLUDED__
#define __FILEB_H_INCLUDED__

int C;
int D;

#endif

//testA.cpp
#include "testA.h"

//testB.cpp
#include <iostream>
#include "testA.h"
#include "testB.h"

int main() {
std::cout << C << std::endl;
}


Prepending "extern" to variable declarations solves these "multiple definition" errors but introduces "undefined reference" errors. I have tried everything I can think of to solve this - but obviously I am doing something wrong.

In case you wonder, in my real application I need the variables to be treated as global variables.

Answer

You should declare global variables in .h file, and define them in .cpp file.

In testA.h

extern int A;

In testA.cpp

int A;

Comments