【问题标题】:Why is this working? I can't understand why my code works in C为什么这行得通?我不明白为什么我的代码在 C 中工作
【发布时间】:2020-09-20 11:25:18
【问题描述】:

我目前正在学习 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。谢谢。

【问题讨论】:

标签: c function header declaration


【解决方案1】:

一般来说,如果你调用了一个没有在任何地方定义的函数,你会看到 linker 的错误,而不是编译器。编译器可能会警告您隐式声明,但通常会放手。

一个例子,使用 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 中运行它,您可能甚至看不到警告消息。因此,即使您认为代码应该有错误,您也会产生一种错觉,即您的代码可以正常工作

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 2012-05-25
    • 2023-04-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多