For my compiler course, I'm following the Incremental Approach to Compiler Construction by Abdulaziz Ghuloum with the accompanying tutorial. At some point, we have the following two .c files:
runtime.c
#include <stdio.h>
int main(int argc, char** argv) {
printf("%d\n", entry_point());
return 0;
}
ctest.c
int entry_point() {
return 7;
}
The author then runs the following commands:
$ gcc -Wall ctest.c runtime.c -o test
[bunch of warnings]
$ ./test
7
$
But when I run $ gcc -Wall ctest.c runtime.c -o test
I get the following error:
runtime.c:9:20: error: implicit declaration of function 'entry_point' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
printf("%d\n", entry_point());
I want to be able to compile and link my two .c files the same way the author did using gcc, but it keeps throwing me that error. I've been doing some research but the same command ($ gcc file1.c file2.c -o combined
) keeps coming up. Help would be appreciated.
I'm running this on MacOS Monterey 12.6 and doing gcc --version
displays:
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Thanks in advance
CodePudding user response:
On macOS, the default compiler is clang
, not gcc
. The later is just a symlink to clang
so that's something to keep in mind.
Clang sees the call to entry_point()
in runtime.c
and doesn't know it yet. Traditional C for such an undefined function is to assume it returns int
and does not accept arguments. But Clang goes the safe route by default and instead of just warning about it, treats this as an error since most of the time this assumption is just false and may cause runtime issues.
You have multiple options:
- Add a header file that defines
int entry_point(void);
and#include
it in yourruntime.c
. - Add the line
int entry_point(void);
near the top of yourruntime.c
. - Pass
-Wno-error=implicit-function-declaration
to the compiler.