Searene
Searene

Reputation: 27654

C ++: Cannot I assign values to a variable in header file?

header.h

int m_linkinfo;
m_linkinfo = 1;

main.cpp

#include "header.h"

int main()
{
    return 0;
}

Failed, with many errors. But if I commented the line m_linkinfo = 1;, everything is OK. Why? Cannot I assign values to a variable in header file? But If I changed the header file to the only one line: int m_linkinfo = 1;, The program is compiled successfully! Why? Is it different from the two lines of code above?

Upvotes: 3

Views: 8596

Answers (3)

paxdiablo
paxdiablo

Reputation: 882726

No, you can't. That's a piece of code so it needs to exist inside a function of some sort, such as:

int main () {
    m_linkinfo = 1;
    return 0;
}

You can, as you have seen, initialise it with:

int m_linkinfo = 1;

however, since that's allowed by the standard.

Keep in mind that it's often risky to define things in header files. By define, I mean statements that create things as opposed to those that simply notify the compiler than things exist (declaring).

That's because including the header in two different translation units can result in two copies of a thing with the same name and, if you subsequently try to link them together, you'll run into trouble.

The best way to solve that is to declare things in header files, such as:

extern int m_linkinfo;

and define them in a non-header (eg, CPP) file:

int m_linkinfo = 1;

That way, every translation unit that includes the header knows about m_linkinfo but only the CPP file creates it.

Upvotes: 9

Timothy Jones
Timothy Jones

Reputation: 22165

C doesn't allow code outside of functions. In your example:

int m_linkinfo;
m_linkinfo = 1;

The second line is illegal, since it isn't in a function.

Outside of functions you can only declare or define variables and functions (or give directions to the preprocessor).

However, you are allowed to initalise a variable when you define it, so you can do this:

int m_linkinfo = 1;

which is perfectly legal.

Upvotes: 5

luser droog
luser droog

Reputation: 19514

Assignment is a statement. Statements are only allowed in functions. The line in the header file is not in a function. Therefore it cannot work.

Upvotes: 0

Related Questions