-1

I'm writing a code for a radio, which contains many child functions and header functions. I've created two headers "simulation_params.h" in which the simulation parameters can be changed, and "global_constants.h", where the look up tables are present. I need to use these two headers at multiple places in my program.

So when I define these headers in two different functions say "main.c" and "scrambling.c". the compiler is showing error, saying "first defined here", "multiple definition of x". I used ifndef and #define in my headers . nevertheless it is showing this error.

  • 2
    Header files should conventionally contain only declarations. – Basile Starynkevitch Oct 16 '14 at 08:50
  • now, cant i initialize the variables inside the header files instead of initializing them inside the source file where it is defined?? –  Oct 16 '14 at 09:14
  • 2
    possible duplicate of [How do I use extern to share variables between source files in C?](http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c) – gnat Oct 16 '14 at 12:03

1 Answers1

0

There is a distinction between declaring and defining variables in C.

Declaring an external variable gives it a name. Defining it allocates memory and initializes it.

A variables can be only defined once. It can be declared in all modules needing it. Normlaly you define a variable in a .c file and share it by declaring it in .h files. The .h file is included by all modules needing the variable.

If you define a variable in a .h file and include the .h file in multiple modules, you have a conflicting definition and the linker wil complain.

So if you need any kind of initialization of a shared constant you need to do create a global_constants.c file and link it with the rest of your modules.

Florian F
  • 1,300
  • 1
  • 12
  • 28