如何使用make和编译为C99?

djT*_*ler 19 linux makefile c99 c89 kbuild

我正在尝试使用Makefile编译linux内核模块:

obj-m += main.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Run Code Online (Sandbox Code Playgroud)

这给了我:

main.c:54: warning: ISO C90 forbids mixed declarations and code
Run Code Online (Sandbox Code Playgroud)

我需要切换到C99.阅读后我注意到我需要添加一个标志-std = c99,不确定它在哪里添加.

如何更改Makefile以便它编译为C99?

Job*_*Job 19

编译模块时添加编译器标志的正确方法是设置ccflags-y变量.像这样:

ccflags-y := -std=gnu99
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅内核树中的Documentation/kbuild/makefiles.txt.

请注意,我使用的是gnu99标准,而不是c99因为Linux内核严重依赖于GNU扩展.

  • 嗨,我将ccflags-y添加到我自己的模块的Makefile中,但编译器仍然警告"ISO C90禁止混合声明和代码".为什么? (3认同)
  • @basicthinker:也许[这个](http://stackoverflow.com/questions/15910064/how-to-compile-a-linux-kernel-module-using-std-gnu99)帮助 (3认同)

oco*_*odo 14

你可以添加

CFLAGS=-std=c99
Run Code Online (Sandbox Code Playgroud)

在您的顶部makefile,或者您可以使代码符合C90(如LukeN建议的那样).


Luk*_*keN -8

和makefile没关系。ISO C90 禁止在块或文件开头以外的任何地方声明变量 - 像这样

int main(int argc, char **argv) {
   int a; /* Ok */
   int b = 3; /* Ok */

   printf("Hello, the magic number is %d!\n", b);
   int c = 42; /* ERROR! Can only declare variables in the beginning of the block */
   printf("I also like %d.. but not as much as %d!\n", c, b);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此必须将其修改为这样......

int main(int argc, char **argv) {
   int a; /* Ok */
   int b = 3; /* Ok */
   int c = 42; /* Ok! */

   printf("Hello, the magic number is %d!\n", b);
   printf("I also like %d.. but not as much as %d!\n", c, b);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

您只能在源代码中“修复”该问题,而不能在 makefile 中“修复”该问题。

这条规则在 C99 中已经放宽,但在我看来,将变量定义、声明和初始化与其下面的代码分开是一个好主意:)

因此,要更改 makefile 以使其使用 C99 进行编译,您需要更改 makefile 引用的“build”目录中的 Makefile,并在编译源文件的“gcc”行添加“-std=c99”。

  • 与编辑编译器的每个调用相比,CFLAGS 更常见、更受青睐,而且更不易损坏。 (8认同)
  • 在 OO (Java) 世界生活了很长一段时间,最近又重新开始更日常地使用 C 后,我不得不不同意将变量信息分离出来的观点。将事情限制在尽可能小的范围内似乎更重要。例如,某些变量仅在 while 或 for 循环内需要。 (6认同)