0

I have two C files 9.c ,10.c.

9.c

#include <stdio.h>
int b=6;
int main()
{
fun1();
printf("%d\n",b);
}
extern int b;

10.c

void fun1()
{
printf("%d\n",b);
b=8;
}

I did gcc 9.c 10.c but it gives following error:

10.c:3: error: 'b' undeclared (first use in this function)

I was expecting that linker would resolve the definition of b, but why its not resolving.

Rishab Shinghal
  • 591
  • 3
  • 16

1 Answers1

3

The line extern int b;, which you have at the end of 9.c, should be at the beginning of 10.c. This tells the compiler that the declaration of b is in another module. See How to correctly use the extern keyword in C.

Updated In reply to your comment, and also to the comments above: When the others say this error is from the compiler, not the linker, they are referring specifically to the "compile" phase of the build process. In this phase, each source file is processed independently. So the fact that you have declared b in 9.c doesn't help the compiler recognize it in 10.c. If you want to delay resolution of this identifier to the linking phase, you need an extern declaration of the variable in 10.c because that's where the declaration is missing.

Having the extern declaration in 9.c is pointless, since the actual declaration occurs earlier in the same file.

I suspect you are thinking of extern as if it means "export", i.e. a command to tell the compiler to remember that b is declared in 9.c so that it can resolve references to it in other files. That's not what it means. It is a command to tell the compiler that this variable is defined externally to the current source file; so you include it in each source file where a variable declared elsewhere is referenced. (Or more typically, it is used in a header file that is included in such source files, such as stdio.h.)

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
  • @user3290550 - Because the problem is in 9.c, not in 10.c. C files are compiled independently. – Oliver Charlesworth Dec 24 '17 at 15:24
  • @OliverCharlesworth , compile error is coming in 10.c , please refer the question. – Rishab Shinghal Dec 24 '17 at 15:27
  • @user3290550 - Ah right. Well you can't put declarations *after* they've been used. – Oliver Charlesworth Dec 24 '17 at 15:28
  • @user3290550. Please see updated answer. The point is not that extern can't be on the last line of a file, the point is that in this case it needs to be in 10.c, prior to the reference to b, and it does not need to be in 9.c at all. – Dave Costa Dec 24 '17 at 15:33
  • @Dave Costa, It was very useful ,only one doubt I have, When we don't include stdio.h and use printf, so how compiler gets assured that there would be definition of printf available. – Rishab Shinghal Dec 24 '17 at 16:18