• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 260
  • Last Modified:

variables declared in two files..

I have 2 cpp files in a project. I added following 2 lines in both the files:
     int c;
     const int p = 10;

When i build this project, I got a linking error that "int c already defined", which is obvious.

I am wondering, why it did not gave the same error for the 'const' variable?

Can anyone please help me on this?

Thanks in advance!
0
payalpr2002
Asked:
payalpr2002
  • 2
  • 2
1 Solution
 
AlexFMCommented:
In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.

This means, const value is defined as static - local to every cpp file where it appears.
0
 
payalpr2002Author Commented:
Thanks. This is clear.
But I am just curious about following things:
1. Is there any specific reason why scope of these const variables is kept local to the file?
2. Does this mean if we apply 'extern' keyword it won't have any effect on const and static variables?
2. Also, can we say that scope of other variables such as 'int a' is global to the application? But we have to use 'extern' keyword to use this variable in other files. That means the scope is not global & it is local to the file. Then why it gave the above error?
0
 
AlexFMCommented:
1. This is done to allow placing const variables to h-file, which must replace #define.
2, 3. extern is not applied to static and const variables, because they are always local.
extern means: there is global variable defined somewhere else. Compiler knows type of this variable, but doesn't care about variable itself, allowing to linker to do this.
Usually it is done by such way:

// definitions.h

extern int n;

// file1.cpp
#include "definitions.h"

int n;        // variable is defined here

// using n variable

// file2.cpp
#include "definitions.h"

// using n variable - compiler knows that it has int type, variable itself is found later by linker
0
 
payalpr2002Author Commented:
Thanks a lot!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now