c++linker-errorsdeclarationdefinitionextern

How to declare some extern variables in a namespace in a header file


I've tried to split my c++ code in multiple files so that it can be cleaner but when I try to test it with building it, I get LNK2005 error.

GlobalVariables.h

#pragma once
#include"ConsolePanel.h"

namespace GlobalVariables {
    extern ConsolePanel CP;

    extern size_t mainDatasetSize = 0;
    extern time_t finishTime;
    extern long double* mainDataset;
    extern long double sum;
    extern int* result;
    extern double resultValue = 0;
    extern bool isThreadsFinished = false;
}

SourceFile1.cpp

#include"GlobalVariables.h"
.
.
.

SourceFile2.cpp

#include"GlobalVariables.h"
.
.
.

I want to use the globalVariables in two seperate files but looks like I can't include the header file in two source files.


Solution

  • In the header

    namespace GlobalVariables {
        extern ConsolePanel CP;
    
        extern size_t mainDatasetSize = 0;
        extern time_t finishTime;
        extern long double* mainDataset;
        extern long double sum;
        extern int* result;
        extern double resultValue = 0;
        extern bool isThreadsFinished = false;
    }
    

    you declared but not defined the following variables with external linkage: CP, finishTime, mainDataset, sum, result. You need to define them in some cpp file by placing their declaration without the linkage specifier extern. Otherwise they will be undefined.

    On the other hand, these variables mainDatasetSize, resultValue, isThreadsFinished were declared and defined because they have initializers. As the header is included in more than one compilation unit then the compiler will issue an error that the variables are redefined. Again you should define them in some cpp file removing their initializers in declarations in the header. There is no need to initialize them explicitly except for readability because by default they in any case will be zero-initialized.

    Pay attention to that in general it is a bad idea to have so many global variables.