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

c, linux, linux-kernel, variables

Solution

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:

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

`EXPORT_SYMBOL` isn't needed.

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

`EXPORT_SYMBOL` is needed.

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

You cannot use such symbol.

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

`EXPORT_SYMBOL` isn't needed.

`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.

Problem

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.

Original source