2

I'm writing the header of a kernel module. The header is known to the module, but also used by callers in user space. This is a problem, because some types used should be included from different files depending on whether the header is currently in user or kernel space (or so this question makes me think).

I don't want to maintain two separate header files, so I've been thinking of a solution like this:

#ifndef IN_KERNEL
#include <stdint.h>
#else
#include <linux/types.h>

With IN_KERNEL being defined somewhere in my kernel code. Is there a preprocessor constant that already does this?

Fadeway
  • 549
  • 5
  • 18

1 Answers1

3

From reading this, it seems that an existing constant used for this purpose is __KERNEL__.

#ifndef __KERNEL__
#include <stdint.h>
#else
#include <linux/types.h>
#endif
Fadeway
  • 549
  • 5
  • 18
  • 1
    And the common practice now is to maintain two headers, one for user space (UAPI), and another for in kernel use. Although the example given by OP is a bit confusing. – 0andriy Jan 07 '18 at 11:10
  • @0andriy: If by *UAPI* you mean header files under `include/uapi`, this is not quite true: These headers are used **both** by kernel code and user one. E.g. types defined in [include/uapi/linux/btrfs.h](http://elixir.free-electrons.com/linux/v3.9.11/source/include/uapi/linux/btrfs.h) are used by btrfs filesystem (implemented in the kernel). – Tsyvarev Jan 07 '18 at 17:10
  • @Tsyvarev, I know. I simplified for the sake of shorter comment. In any case there is still confusion what OP is trying to do with them (based on example `stdint.h` is not **kernel** related header at all). – 0andriy Jan 08 '18 at 10:38
  • Example uses `stdint.h` as a **non-kernel** header (`#if*n*def`) and `linux/types.h` as kernel one. I see no confusion in that. – Tsyvarev Jan 08 '18 at 12:07
  • @Tsyvarev, *I'm writing the header of a kernel module.* This is a contradiction. The part in the example shouldn't be in the kernel header even if it is a UAPI one. – 0andriy Jan 12 '18 at 00:04
  • @0andriy: Don't get your point. Code in the example could perfectly be part of a header under `include/uapi`, which is accessible for a kernel module during compilation, and which can be installed, so user can access it too. – Tsyvarev Jan 12 '18 at 07:36
  • No, it can’t (technically yes, though it would be abuse of a common sense). One more time and I am going to rest my case, *stdint.h* has nothing to do with kernel. It must not be in a **kernel** part of headers. – 0andriy Jan 12 '18 at 11:11