我目前正在学习C,并且遇到了这种奇怪的行为(基于我的理解):
我有2个文件:
文件1.c
#include <stdio.h>
int main()
{
printNumber(2);
return 0;
}
文件2.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中运行此程序,则可能甚至看不到警告消息。因此,您有一种幻想,即使您认为代码应该有错误,代码也能正常工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句