Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variables in header C++

EDIT: correct function names, and added #pragma once

This is a very strong simplification of my problem, but if I do this:

A.h

#pragma once
static int testNumber = 10;
void changeTestNumber();

A.cpp

#pragma once
#include "A.h"

void changeTestNumber()
{
    testNumber = 15;
} 

B.h

#pragma once
#include "A.h"
// some other stuff

B.cpp

#pragma once
#include "B.h"
// some other stuff

main.cpp

#pragma once
#include "B.h"
#include <iostream>

int main(){

changeTestNumber();
std::cout<<testNumber<<std::endl;

return 0;
}

Why am I not getting testNumber = 15 at the call out? What really happens when I use a function that is included in a header of my included header? If I remove the static in from of int testNumber, I will get some error about my testNumber being initialized twice.

So is my header compiled twice when I do this?

Thanks in advance!

like image 808
remi Avatar asked Dec 07 '22 23:12

remi


1 Answers

Aside from the obvious incorrect naming (which I assume was simply a matter of hastily creating an analogous example and is not the actual issue in your code), you need to declare the variable as extern in your .h/.hpp file. You cannot have an extern variable that is also static since the (one of the) use(s) of static is to keep the variable contained to within a single .cpp file.

If you change:

static int testNumber = 10;

in your A.h file to:

extern int testNumber;

and then in your A.cpp file do something like:

#include "A.h"
int testNumber = 10;

Now go ahead and run:

int main() {
    //changeNumber();
    std::cout << testNumber << std::endl; // prints 10
    changeTestNumber(); // changes to 15
    std::cout << testNumber << std::endl; // prints 15
    std::cin.ignore();
    return 0;
}

Be sure to fix the function names!

like image 84
Goodies Avatar answered Dec 22 '22 16:12

Goodies