bholanath
bholanath

Reputation: 1753

Compilation Error for extern variable initialized in other file

I have these two different program where I want to access the static variable declared in program1 from program2.

Program1. ( /* file a.c */)

#include<stdio.h>    

static int a = 100; /* global static variable not visible outside this file.*/
int *b = &a; /* global int pointer, pointing to global static*/

Program2

#include<stdio.h>
/* file b.c */
extern int *b; /* only declaration, b is defined in other file.*/

int main()
{
        printf("%d\n",*b); /* dereferencing b will give the value of variable a in file a.c */
        return 0;
}

While I compile program1 , gcc a.c , no compilation error, but while I compile program2 ( gcc b.c) I am getting compilation error .

test_b.c:(.text+0x7): undefined reference to `b'
collect2: error: ld returned 1 exit status

Why there is compile error ? Here is the link of program static

Thanks in advance.

EDIT 1:

My intention to use static variable from other program. I thought every .c program must have main() function and only .h program have declaration , I am wrong at that point. So I remove main() function from a.c program and instead of compiling two different program separately , now I compile only once using gcc a.c b.c as per suggestion of Filip. Now it's working fine. Thanks all of you.

Upvotes: 0

Views: 861

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Well, your code already said it. b.cpp only has a declaration, not a definition, of the symbol in question.

Since these are clearly meant to be source files from two separate projects, I would suggest moving your definition to its own .cpp file which may then be shared between the two projects.

$ gcc a.c myIntPointerIsHere.c
$ gcc b.c myIntPointerIsHere.c

However, there are clearer ways to share code between two different projects.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The both modules contain the definition of main. It seems that the compiler did not include the first module in your project. Otherwise I think it would issue an error that main was redefined.

Upvotes: -1

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

You have to link against a.c while compiling b.c:

gcc a.c b.c

You can't expect the linker to magically find the C file where b is defined. extern means it is defined elsewhere - you have to say where. By compiling and linking with a.c, the linker can now find a declaration for b.

Of course, you can't have 2 main() functions.

Upvotes: 1

Related Questions