I have the following two files:
file1.c
int main(){
foo();
return 0;
}
file2.c
void foo(){
}
Can I compile and link the two files together so the file1.c
will recognize the foo
function without adding extern
?
Updated the prototype.
gcc file1.c file2.c throws: warning: implicit declaration of function foo.
You can properly include . C or . CPP files into other source files.
A large C or C++ program should be divided into multiple files. This makes each file short enough to conveniently edit, print, etc. It also allows some of the code, e.g. utility functions such as linked list handlers or array allocation code, to be shared with other programs.
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
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With