如何阅读 CLion 中 C 库的源代码

How do I read the source code for a C library in CLion

我是一个刚开始学习C语言的新人。当我使用 CLion 编写 C 代码时,我可以通过 Ctrl + mouse click 访问它。

我正在调用 header 函数中的方法。例如,如果我使用 printf ,我可以访问 stdio.h 文件,可以在第 332 行看到 extern int printf (const char * ___, RESTRICT, format,...) ; .

但是如果我想看这个方法的细节

我看不到。根据Navigate in the code structure

使用Ctrl+Alt+Home切换。但是 IDE 提示 No related file .

如何获取调用方法的源代码?我想通过查看他们库中的实现逻辑来学习其他人的良好经验

感谢您的评价。如果你能帮助我,我将不胜感激。

即使大多数 GNU/Linux 软件是 open source,它也不会默认安装(以源代码形式)在您的计算机上。

关于 C 编程,参见 Modern C (and the C11 standard n1570) and read the documentation of your C compiler (perhaps GCC or Clang, or simpler ones like nwcc or tinycc), your linker (probably binutils), your build automation tool (e.g. GNU make or ninja or cmake). Enable all warnings and DWARF debug info, so if using GCC compile with at least gcc -Wall -Wextra -g; then improve your C code to get no warnings. Once you have debugged your C source code (using GDB and perhaps valgrind),添加优化标志,例如 -O2gcc 的参数顺序很重要!

考虑,对于某些任务,使用 GNU bison, ANTLR, SWIG, RPCGEN, AWK, GUILE, GPP, GNU m4, GNU autoconf 之类的工具或您自己的程序或脚本生成一些 C 代码(可能是一些 #include-d 头文件)。

I want to learn from the good experiences of others by looking at their implementation logic in their libraries

您需要从别处获取源代码。

有关示例,请参阅 GNU libc or musl-libc, and the Linux kernel (and others: GTK, PostGreSQL, sqlite, GUILE, etc.... including many open source programs mentionned in this answer) and look also on websites like github, gitlab, sourceforge

另读Advanced Linux Programming and syscalls(2). See also http://linuxfromscratch.org/

2020 年,最近 GCC compiler happens to handle specially calls to printf when asked to optimize. See the softwareheritage and Frama-C 个项目。

在某些情况下,考虑接受 plugins in your program with dlopen(3) and dlsym(3) (see also elf(5) and How to Write Shared Libraries). You might even generate some code at runtime with libraries like libgccjit (or generate C code at runtime, then compile it as a plugin, and load it; such an approach is called metaprogramming and is related to partial evaluation; see also the blog of the late J.Pitrat 以获得更多见解)。

当然,您需要工具来在源代码中导航。考虑使用 GNU emacs combined with GNU grep for that, or some other source navigator. For large programs of millions of source code lines, consider writing your own GCC plugin 来理解它们。

还可以使用 strace(1) and GDB 等工具来了解程序的动态行为。

期待几个月的全职工作来探索这一切。

您可能也会对 ACM 会议论文感兴趣。

对于您自己的源代码,请考虑使用一些 version control tool such as git. Of course read its documentation. And use LibreOffice, Lout or LaTeX, MarkDown (perhaps combined with inkscape or diagrams 的图形)来编写您的软件的文档。

在某些情况下,您可能会考虑从部分源代码生成部分文档(例如使用 literate programming techniques like nuweb or documentation generators like doxygen)。