Compiling multiple C files in a program
You don't need an extern
, but file1.c must see a declaration that foo()
exists. Usually this declaration is in a header file.
To add a forward declaration without using a header file, simply modify file1.c to:
int foo(); // add this declaration
int main(){
foo();
return 0;
}
The correct way is as follows:
file1.c
#include <stdio.h>
#include "file2.h"
int main(void){
printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__);
foo();
return 0;
}
file2.h
void foo(void);
file2.c
#include <stdio.h>
#include "file2.h"
void foo(void) {
printf("%s:%s:%d \n", __FILE__, __func__, __LINE__);
return;
}
output
$
$ gcc file1.c file2.c -o file -Wall
$
$ ./file
file1.c:main:6
file2.c:foo:6
$