问题
I have two files: test1.c
, and test2.c
, which contains the main()
function.
test1.c:
#include <stdio.h> // printf() function declaration/prototype
// function definition
void say_hello() {
printf("\tHello, world!\n");
}
test2.c:
#include <stdio.h> // printf() function declaration/prototype
int main() {
printf("Inside main()\n");
say_hello();
return 0;
}
And this is my makefile:
a.out: test1.o test2.o
$(CXX) -o a.out test1.o test2.o
test1.o: test1.c
$(CXX) -c test1.c
test2.o: test2.c
$(CXX) -c test2.c
Now it should be clear where the problem lies: The main() function in test2.c calls say_hello() without declaring it!
I run the following command, to use the gcc compiler:
make CXX=gcc
I get this warning to the screen:
gcc -c test1.c
gcc -c test2.c
test2.c: In function ‘main’:
test2.c:16:3: warning: implicit declaration of function ‘say_hello’ [-Wimplicit-function-declaration]
say_hello();
^
gcc -o a.out test1.o test2.o
Although the *.o files got compiled and linked into the executable. That's weird. Imagine my surprise when I run the a.out file, and I see that main()
successfully called say_hello()
, a function which is not declared inside of main's translation unit, as if there were no issue at all! I reason that since say_hello()
was not previously declared in test2.c
, it should not allowed to be called by main()
at all. Notice that I've added comments to the #include <stdio.h>
. These preprocessor directives include the function declarations/prototypes, which extend their scope into the corresponding *.c files. That is why we are able to use them. No function declaration/prototype == no scope in that translation unit, or so I thought until now.
Then I compiled the above code as C++ code:
make CXX=g++
I get this error to the screen:
test2.c: In function ‘int main()’:
test2.c:16:13: error: ‘say_hello’ was not declared in this scope
say_hello();
^
makefile:18: recipe for target 'test2.o' failed
make: *** [test2.o] Error 1
g++ does what it's supposed to do, and stops the compilation process. But gcc did not do this! What's going on? Is it a perk of the C programming language? Is it an issue with the compiler?
回答1:
Simple, because C allows undeclared functions to be called and C++ does not. Either way, gcc
warns you and you may want to take warnings seriously.
来源:https://stackoverflow.com/questions/50496264/why-does-c-allow-me-to-call-an-undeclared-function