2

I got another question in C programming. I followed an example in the Book "Programming in C" and wrote the following two source files:

main.c:

#include <stdio.h>
#include <stdlib.h>

int i = 5;

int main(void)
{
  printf("%i ", i);

  foo();

  printf("%i\n", i);

  return 0;
}

and foo.c:

extern int i;

void foo(void)
{
  i = 100;
}

Problem arises when I compile 'gcc main.c foo.c':

main.c:9:3: warning: implicit declaration of function 'foo' is invalid in C99 [-Wimplicit-function-declaration] foo(); ^ 1 warning generated.

I found a work around by renaming foo.c to foo.h and include it as header in main.c. Is this a good way of making it work? How to make it work with foo.c ?

TonyW
  • 18,375
  • 42
  • 110
  • 183

2 Answers2

7

You need a header with declaration of the function foo. Leave foo.c as is and create foo.h with the declaration

void foo(void);

Then include foo.h in main.c and in foo.c:

#include "foo.h"
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
2

You need to define the signature of foo in a header and include it in main.c

foo.h:

void foo(void);

in main.c:

#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
// Rest of code
dtech
  • 13,741
  • 11
  • 48
  • 73