Re: Defining new variables for use in multiple c files. How do I create header files that can be #included in multiple c files?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Jul 9, 2008 at 9:56 PM, Bradley Hanna <brahan.ml@xxxxxxxxx> wrote:
> I am trying to define a variable that needs to be manipulated by one c
> file in the kernel and read by another c file in a different directory.
> I have defined the variable in a header file that is #included in both c
> files.

A variable can be DECLARED multiple times but only DEFINED once.

Define means give it real memory space, and declare means like saying
the compiler "someone else allocated this variable, and I just want to
use it". Get the point?

So you should define it on a single module (int var), and put its
declaration on a header file, like

extern int var;

Whenever you link a module with the one that defines the variable, you
should #include the header file that declares it. For example:

var.c:
---8<------
int var; /* variable defined: compiler actually allocates space */
---8-<-----

var.h:
---8<------
#ifndef VAR_H /* Rembember, symbols beginning by "_" are reserved by
the compiler */
#define VAR_H

extern int var; /* variable declared. Just state its type and make it
"available" */

#endif
---8<-----

use.c
---8<-----
#include "var.h"

int main(void) { /* you are compiling -ansi -pedantic, aren't you? */
    var++;

    return 0;
}
---8<-----

Makefile:
---8<-----
use: use.c var.c var.h
     gcc -ansi -pedantic -Wall -o use use.c var.c
---8<-----

Cheers
-- 
Alberto Giménez

--
To unsubscribe from this list: send an email with
"unsubscribe kernelnewbies" to ecartis@xxxxxxxxxxxx
Please read the FAQ at http://kernelnewbies.org/FAQ



[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux