Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const, static, extern and their combinations in C and C++ [closed]

Tags:

c++

c

1) How are static, extern and const and their use is different in C and C++? (Default Linkage and other differences)

2) Following declarations and definitions are allowed in a header file used in C which is then included in multiple files.

static int testvar = 233;
extern int one;
extern int show();
int abc;
const int xyz;  // const int xyz = 123; produces error

The const definition produces and error during compilation(maybe because of multiple definitions). However I can declare a const variable in header file but since we can define it providing a value and neither can we assign a value in the files this header is included in, it effectively is useless. Is there a way to define const in a header file and then access it in multiple files by including the header?

3) What changes(if at all) needs to be done so that this header can be included in multiple files in C++?

4) consider the following

header.h

static int z = 23;

test.c

#include"header.h"

z = 33;  //gives error redefinition of z!!!??

void abc()
{
    z = 33;  //perfectly fine here!!??
}

static vars defined/declared in header have internal linkage in each file means each file will have a separate copy of that variable. Then why does assigning a value to that var outside any function gives redefinition error while it is perfectly file inside a function?

Edit: added a 4th question. This is very confusing.

**PS: Now I am looking for answers to question 1 and 4 only.

like image 668
Yogender Singh Avatar asked Jan 16 '23 09:01

Yogender Singh


2 Answers

1)

static means to not put an object in the global symbol table. On the plus side, you can have multiply defined symbols without a problem. On the down side, there aren't symbols generated for any static variables/methods, so it can make debugging harder.

2&3)

In the header:

extern const int xyz;

In a source file that includes the header (ideally the same .cc whose name matches the .h):

const int xyz = 123;

This way everyone knows about xyz but it's only defined in one source file.

like image 169
DigitalGhost Avatar answered Jan 30 '23 14:01

DigitalGhost


I can declare a const variable in header file but since we can define it providing a value and neither can we assign a value in the files this header is included in, it effectively is useless.

If you want an externally-linked symbol, you can declare it in the header file and then define it in exactly one of your source files. You get to choose which one.

However, for a const int there's usually no point it having external linkage. Just give it internal linkage with static const int xyz = 123; in the header.

That's for C: in C++ const globals have internal linkage by default.

like image 29
Steve Jessop Avatar answered Jan 30 '23 15:01

Steve Jessop