UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » extern variable

#1 2008-11-05 08:50 AM

Jana
Member
Registered: 2008-03-24
Posts: 21

Re: extern variable

Hi following code snippet

File f1.c
---------
#include <stdio.h>

struct ABC {
  int a;
  int b;
  int c;
};
struct ABC abc;
abc.a=10;

File f2.c
----------
1 #include <stdio.h>

3 extern struct ABC abc;

5 main()
6 {
7     int k=0;
   
9     k=abc.a;
10 }

compile both files
----------------
$gcc f1.c f2.c  -o a.out 

Compilation giving following error
f2.c:9: error: invalid use of undefined type 'struct ABC'

Could you tell me why it is giving error ?

Offline

#2 2008-11-05 09:43 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: extern variable

Because it fails to compile f1.c:

$ gcc f1.c f2.c -o a.out
f1.c:9: error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
f2.c: In function 'main':
f2.c:9: error: invalid use of undefined type 'struct ABC'

"abc.a=10;" is code which can't float around, but must be in a function.

But if you want to initialize a to 10, then declare abc as follows:

struct ABC a = {10, 0, 0};

struct ABC b = {10}; // works because 'a' is the first one

struct ABC c = {.a = 10}; // C99 style

The next problem is that f2.c doesn't know about what you do in f1.c.

So instead of defining the structure in f1.c, define it in f1.h and include f1.h
in both f1.c and f2.c. Only definitions used within one c file are defined in a
c file, the rest should be defined in a header file and be included by all files
needing it.

You also want to avoid using things like "extern struct ABC a" in c files.
Instead put that in f1.h as well.

Offline

  • Index
  • » C
  • » extern variable

Board footer

Powered by FluxBB