For Linux device driver programming, why I can use APIs like `sysfs_create_group` without `linux/sysfs.h` header?

142 Views Asked by At

When I compiled a device driver with APIs like sysfs_create_group or attributes declaration without including linux/sysfs.h, I found that the driver can still be compiled, and the driver worked fine with the device. Furthermore, I had searched other headers included in the driver, such as linux/module.h, linux/i2c.h, or linux/device.h, none of them includes linux/sysfs.h.

I assume the APIs are exported by the kernel, so the loaded driver is able to call the function. In that case, is it okay not to include linux/sysfs.h? or is it caused by other reasons?

I have just begun to learn C and device driver programming recently, so the question might be unclear.

The Linux kernel version I used is 5.15.

1

There are 1 best solutions below

1
pmacfarlane On

One of your include files will be including linux/sysfs.h, possibly indirectly, i.e. it includes a file, which includes a file, which includes sysfs.h. Possibly nested even deeper than that. You could compile your code with the -E option to gcc to see the pre-processed output. That should show you where the include came from.

Relying on other header files to #include files that are required to build your code is fragile and not recommended, especially if you don't even know which one it is. Maybe in the future you won't #include whichever one happened to bring in sysfs.h, and then your code won't compile. Or maybe a future version of that header file won't include sysfs.h.

If your code explicitly uses something provided by a header file, you should #include it yourself.