Jaeya Jaeya - 5 months ago 32
C++ Question

Multiple definitions and undefined references

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

#ifndef __FILEA_H_INCLUDED__
#define __FILEA_H_INCLUDED__

int A;
int B;


#ifndef __FILEB_H_INCLUDED__
#define __FILEB_H_INCLUDED__

int C;
int D;


#include "testA.h"

#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.


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;