为什么这是有效的?我不明白为什么我的代码可以在 C 中运行

Why is this working? I can't understand why my code works in C

我目前正在学习 C,我遇到了这种奇怪的行为(根据我的理解):

我有 2 个文件:

file1.c

#include <stdio.h>

int main()
{
    printNumber(2);
    return 0;
}

file2.c

void printNumber(int number)
{
    printf("Number %d is printed.", number);
}

输出:

Number 2 is printed.

为什么我没有收到声明错误?我认为你需要在文件中的某处声明一个函数(或者更好的头文件)

我搜索了论坛试图得到答案,但我看到有人使用非常相似的代码得到了错误,但不知何故我没有得到它...

顺便说一句,我正在使用 GCC 和 C11。谢谢

一般来说,如果您调用一个未在任何地方定义的函数,您会看到 链接器 的错误,而不是编译器。编译器可能会给您警告隐式声明,但通常会放过它。

一个例子,使用 gcc 8.3 编译你的 file1.c:

$ gcc -o test file1.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
/usr/bin/ld: /tmp/ccs0wv7L.o: in function `main':
file1.c:(.text+0xf): undefined reference to `printNumber'
collect2: error: ld returned 1 exit status

请注意,警告来自编译器,但只有 ld(链接器)会给出未定义函数引用错误。

所以我怀疑你像下面这样编译程序,链接器足够聪明,可以关联目标代码:

$ gcc -o test file1.c file2.c
file1.c: In function ‘main’:
file1.c:5:5: warning: implicit declaration of function ‘printNumber’ [-Wimplicit-function-declaration]
     printNumber(2);
     ^~~~~~~~~~~
file2.c: In function ‘printNumber’:
file2.c:3:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
     printf("Number %d is printed.", number);
     ^~~~~~
file2.c:3:5: warning: incompatible implicit declaration of built-in function ‘printf’
file2.c:3:5: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
file2.c:1:1:
+#include <stdio.h>
 void printNumber(int number)
file2.c:3:5:
     printf("Number %d is printed.", number);
     ^~~~~~

您看到上面的警告,但它实际上编译并且链接器没有抱怨。如果您 运行 在您的 IDE 中看到这个,您可能甚至看不到警告消息。所以你有一种错觉,即使你认为它应该有一个错误,你的代码仍然有效