c - c 中导入的头文件使用了哪些函数?

标签 c header

我正在阅读这个用 C 语言编写的庞大代码库。在某些文件中,包含了一些 header ,但未指定是否需要这些 header 。我想知道是否有任何方法可以查看当前文件中特定 header 使用了哪些函数,而无需通读两个文件中的整个代码。

最佳答案

最简单的方法是检查预处理文件。编译器的预处理器将生成声明或定义来自哪个文件的信息。

使用 GCC 或 Clang,使用 -E 等标志生成预处理代码。

例子

以helloworld修改版为例。修改代码以包含更多头文件。

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
        char * str = (char*) malloc(sizeof(char)*10);
        int16_t a = 10;
        str[0]='h';str[1]='e';str[2]='l';str[3]='l';str[4]='o';str[5]='\0';
        printf("%s %d\n", str, a);
        free(str);
        return 0;
}

在我的 Ubuntu 15.04 中,使用 gcc -E hello_mod.c -o hello_mod.i。预处理后的文件如下,无关代码已被删除。

<......UNRELATED CODE REMOVED.......>

# 36 "/usr/include/stdint.h" 3 4
typedef signed char int8_t;
typedef short int int16_t;
<......UNRELATED CODE REMOVED.......>


# 319 "/usr/include/stdio.h" 3 4
<......UNRELATED CODE REMOVED.......>

extern int printf (const char *__restrict __format, ...);

<......UNRELATED CODE REMOVED.......>


# 315 "/usr/include/stdlib.h" 2 3 4

<......UNRELATED CODE REMOVED.......>

extern void *malloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;

<......UNRELATED CODE REMOVED.......>

extern void free (void *__ptr) __attribute__ ((__nothrow__ , __leaf__));


<......UNRELATED CODE REMOVED.......>
# 1 "/usr/include/x86_64-linux-gnu/bits/stdlib-float.h" 1 3 4
# 955 "/usr/include/stdlib.h" 2 3 4
# 967 "/usr/include/stdlib.h" 3 4

# 4 "hello_mod.c" 2

int main() {
        char * str = (char*) malloc(sizeof(char)*10);
        int16_t a = 10;
        str[0]='h';str[1]='e';str[2]='l';str[3]='l';str[4]='o';str[5]='\0';
        printf("%s %d\n", str, a);
        free(str);
        return 0;
}

通常,原始代码位于预处理器生成的文件的末尾。然后您可以向后搜索您感兴趣的功能。一旦找到它。然后向后滚动时第一个以#开头的文件路径就是函数声明的头文件。

根据上面的代码,我们可以发现:

  • int16_ttypedef 文件 /usr/include/stdint.h
  • printf 函数在 /usr/include/stdio.h 中声明。
  • mallocfree 函数在 /usr/include/stdlib.h
  • 中声明

编译器也使用这种方式生成调试信息,帮助您在 gdb 中找到文件路径和行号。

关于c - c 中导入的头文件使用了哪些函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269844/

相关文章:

C、Contiki rime,传输结构

c - 错误 : variable-sized array may not be initialized

python - websockets.exceptions.InvalidStatusCode : server rejected WebSocket connection: HTTP 400

css如何将一个标题单元格合并到一个单元格中

php - 我想要在 PHP 中使用 header() 的自定义 < title >

c - 为什么程序在 scanf 上停止...如果删除该行它可以正常工作

c - 如何在 pthread 函数 usleep() 的 for 循环中使用随机种子生成器?

c - 如何在 C 中使 0 成为 int 数组的一部分?

c - 如何在 header 中声明外部二维数组?

linux - 如何在Linux上查找指定目录中所有使用特定 header 的文件?