Extern variable problem

i have the following code
1
2
3
4
5
6
7
8
9
THIS IS A.cpp
int a=5;
int inc();
int main()
{
printf("value of a is %d\n",a);
a++;
inc();
}


i have another file which look like below

1
2
3
4
5
6
THIS is b.c
extern int a;
int inc()
{
printf("value of a is %d\n",a);
}


When i compile the following code i am getting the error that is
error LNK2001: unresolved external symbol _a

What is the error?
Where are your includes? How are you compiling the two files into a single executable?
The problem is that inside the first module named A.cpp name a has C++ language linkage that is it in fact is declared as

extern "C++" int a;
int a = 5;

While inside the second module named b.c name a has C language linkage because this module was compiled as C-code by the compiler.

So this name denotes two different entities in your project.

There are two methods to avoid the error.

The first is to compile the second module as C++ code. I think it will be enough to rename the module from b.c to b.cpp.

The second is to declare variable a as having the C language linkage in the first module

extern "C" int a = 5;


It is better even to combine the variable and the function in one language linkage specification in the fiirst module because the function also has C langauge specification

1
2
3
4
5
6
extern "C"
{
   int i = 5;
   int inc();
}
Last edited on
Topic archived. No new replies allowed.