6
votes

I'm trying to write a kernel module but I'm stuck with accessing member of structure defined in another module header. I'll try to explain:

Let's say the other module is:

<kernel-src>/drivers/xxx/xxx.c|.h

in xxx.c there are some exported functions which I'm using in my driver. However I want to access the member m1 from struct s_xxx defined in xxx.h:

struct s_xxx {
    ...
    int m1;
};

Next I have this in /usr/include/linux/yyy.h:

struct s_xxx;
struct s_yyy {
    ...
    struct s_xxx *p_xxx;
};

I my driver I've:

#include <linux/yyy.h>

and I'm successfully using the exported symbols from the xxx driver. But of course if I try to access member from s_xxx the compiler complains:

struct s_yyy *p_yyy;
...
m = p_yyy->p_xxx->m1; /* error */

xxx.h can't be found in /usr/include/linux/. So far I've found 2 workarounds:

1) to download the kernel sources and include the full path to xxx.h in my module

2) copy/paste the s_xxx definition from xxx.h to my module

What is the correct way to do this?

(sorry for the long and crappy explanation :@ )

1
OK, almost all of the Answers are about including the yyy.h file. However I can't do this because it's not included in the kernel headers. Its only in the module location in the kernel sources. So if I want to distribute the SW the user have to download the kernel sources as well to be able to build. And this is not an option.Meh
well, if xxx.h is not in include/linux/... that means that this header is not a part of xxx module public interface and probably there is a good reason for this, imo neither of your solutions is acceptable, make sure you are not overlooking an interface function that does what you want and it is not the case propose interface extension with good reasoning to module maintainerRaber

1 Answers

5
votes
struct s_xxx;
struct s_yyy {
    ...
    struct s_xxx *p_xxx;
};

In absence of xxx.h this means you have a forward declaration of struct s_xxx and you can declare pointers to it, but you can't use its members yet or instantiate one, because its size or members aren't known to the compiler. You need to include the full structure definition by including xxx.h in the compilation unit.

If xxx.h is not part of xxx's public interface but you still insist on accessing the internals of the module you face the risk of a catastrophic compatibility break in the future if the internal structure of xxx is changed.

It is not advisable to copy the structure definition to your own code because binary compatibility between the structures cannot be guaranteed, unless you have built everything yourself with the same compiler and options.