是否有宏定义来检查 Linux 内核版本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16721346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:00:39  来源:igfitidea点击:

Is there a macro definition to check the Linux kernel version?

clinuxgccmacroslinux-kernel

提问by zztops

I'm wondering if there is a gcc macro that will tell me the Linux kernel version so I can set variable types appropriately. If not, how would I go about defining my own macro that does this?

我想知道是否有一个 gcc 宏可以告诉我 Linux 内核版本,以便我可以适当地设置变量类型。如果没有,我将如何定义自己的宏来执行此操作?

采纳答案by Vilhelm Gray

The linux/version.hfile has a macro called KERNEL_VERSIONwhich will let you check the version you want against the current linux headers version (LINUX_VERSION_CODE) installed. For example to check if the current Linux headers are for kernel v2.6.16or earlier:

LINUX / version.h中的文件有一个名为宏KERNEL_VERSION可以让你检查要对当前的Linux版本头(版本LINUX_VERSION_CODE)安装。例如,检查当前的 Linux 头文件是否适用于内核v2.6.16或更早版本:

#include <linux/version.h>

#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,16)
...
#else
...
#endif

A better way to get the version information at run-time is to use the utsnamefunction in include/linux/utsname.h.

在运行时获取版本信息的更好方法是使用include/linux/utsname.h 中utsname函数。

char *my_kernel_version = utsname()->release;

This is essentially how /proc/versiongets the current kernel verison.

这基本上是/proc/version获取当前内核版本的方式。

See also

也可以看看

Getting kernel version from linux kernel module at runtime

在运行时从 linux 内核模块获取内核版本

回答by ldav1s

gccwon't know this information. As an alternative, you can determine a lot of kernel information at runtime easily.

gcc不会知道这些信息。作为替代方案,您可以在运行时轻松确定大量内核信息。

You can define your runtime type like

您可以定义您的运行时类型,如

struct unified_foo {
     unsigned int kernel_version;
     union {
         kernel_x_foo_type k_x;
         kernel_y_foo_type k_y;
         kernel_z_foo_type k_z;
     } u;
};

and have code at runtime look at /proc/version(or whatever you need from the kernel runtime environment) and set kernel_versionapproriately. The kernel_x_foo_typeet al. is your type that you want to be conditional on the kernel version. The calling code needs to look at kernel_versionand access the appropriate u.k_x, u.k_y, or u.k_zdata.

并在运行时查看代码/proc/version(或任何您需要的内核运行时环境)并进行kernel_version适当设置。在kernel_x_foo_type等人。是您希望以内核版本为条件的类型。调用代码需要查看kernel_version和访问适当的u.k_xu.k_yu.k_z数据。