Hunter
Hunter

Reputation: 43

How to use a variable from another c file in linux kernel?

I know the way normal and I tried it but it seems not work.

In linux/net/sched/sch_htb.c, I define the variable:

unsigned int queuelength;
EXPORT_SYMBOL(queuelength);

And some actions about the variable, not important.

In linux/net/ipv4/tcp_dctcp.c,

extern unsigned int queuelength;

Error come with net/built-in.o:

In function `dctcp_update_alpha':
linux/net/ipv4/tcp_dctcp.c:230: undefined reference to `queuelength'

The kernel version is v4.6.

Upvotes: 4

Views: 832

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65928

It depends on how a source file, which defines the variable (generally, symbol), and a source file, which uses the variable (symbol) are compiled: as a part of the kernel module, or as a part of the kernel core (that is, built-in into kernel).

Assuming names of the source files are define-symbol.c and use-symbol.c correspondingly, you have 5 possibilities:

  1. Both define-symbol.c and use-symbol.c are compiled into kernel core.

    EXPORT_SYMBOL isn't needed.

  2. define-symbol.c is compiled into kernel core, use-symbol.c is compiled into kernel module.

    EXPORT_SYMBOL is needed.

  3. define-symbol.c is compiled into kernel module, use-symbol.c is compiled into kernel core.

    You cannot use such symbol.

  4. define-symbol.c and use-symbol.c are compiled into the same kernel module.

    EXPORT_SYMBOL isn't needed.

  5. define-symbol.c and use-symbol.c are compiled into the different kernel modules.

    EXPORT_SYMBOL is needed.

Note, that way of source compilation may depend on configuration options.

In your case, it seems you have situation 3: as net/ipv4/tcp_dctcp.c is used for built-in.o, it is part of the kernel core.


Note, that in any case variable should be declared for use it. Otherwise, it will be compile-time error, not a link one.

Upvotes: 3

Related Questions