Hi!

On Thu Oct 16, 2003 at 01:51:18PM +0800, James Ng Yuen Sum wrote:
> I am a newbie in using linux and C language. I want to ask how to use
> "extern". In C language, we can have two .c file, in one file the
> variable(s) can be open for other .c file use if extern is the storage
> class of the variable.
> 
> But my teacher has told me that in gcc, I have to use Makefile to do it.
> But I do not know how to do that in gcc.

Aeeg, wrong.

Say you have 2 C files:


/* hugo.c */

/* global variable, can be accessible in other C files */
int hugo;

/* EOF */

-------------------

/* foobar.c */

/* Variable hugo uses no storage space in foobar.o
 * the compiler just see this declaration and can 
 * check for the valid use of hugo.
 * It's better, if you have a header file for such
 * extern declarations (maybe hugo.h ;-).
 */
extern int hugo;

/* this function sets hugo to n. hugo is not in
 * foobar.o but in hugo.o
void
foobar (int n)
{
        hugo = n;
}

/* EOF */


So to compile those to C files to object files you can do the following:

$ gcc -c hugo.c -o hugo.o
$ gcc -c foobar.c -o foobar.o

To use the function foobar() you have to link your code (say main.o) to
hugo.o and foobar.o like this:

$ gcc main.o foobar.o hugo.o -o foobar

This will link an executable named foobar. You see there's nothing
special about extern linkage in gcc.

To avoid the hassle with commandline compiles it's better to use
Makefiles. There's a good manual at [1].

So long
Thomas

  1. http://www.gnu.org/manual/make/

-- 
 .''`.  Obviously we do not want to leave zombies around. - W. R. Stevens
: :'  : Thomas Krennwallner <djmaecki at ull dot at>
`. `'`  1024D/67A1DA7B 9484 D99D 2E1E 4E02 5446  DAD9 FF58 4E59 67A1 DA7B
  `-    http://bigfish.ull.at/~djmaecki/

Attachment: pgp00000.pgp
Description: PGP signature

Reply via email to