Question

I am a beginner to C programming and I'm trying out different methods and experimenting with small programs.

I have four files. two header files and two source files. I want to:

  1. Declare a variable (Actually two variables and a char) and a function (from the second source file) in one header file.
  2. Define these variables and assign values to them in a second header file(variables from point 1).
  3. Write a function including these two header files and using the values from these files(point 2) in one source file (without a main- just a function definition using the variables).
  4. Have a main source file that invokes the function from the second source file (from point 3.)

How do I come about this? I have included both header files in both the .c files. But when I try to compile and link it (using GCC in Linux) I get a multiple definition ... first defined here error for all the variables.

I have looked at these answers First and Second I didn't quite understand the answers in the Second as I'm not able to figure out how to use header guards. I am not able to figure out how to check all of the boxes (points one through 4).

header1.h

extern int i,j; extern char c;
void ad_d();

header2.h

int j=6;int i=7;
char c='x';

fnfile.c

#include "header1.h"
#include "header2.h"
#include<stdio.h>

void ad_d()
{

    i+=j;

    printf("\n %d \t %c \n", i,c);
}

filemain.c

#include<stdio.h>
#include "header1.h"
#include "header2.h"



void main()
{

    ad_d();
}
Was it helpful?

Solution

You can only define a variable once, that allcoates space in memory where the value will be stored. you can then declare the variable in each file (or better yet in a common header file) which will tell the compiler that a varialble of that name and type will be defined in one of the compiled files, and can be found at a later stage.

in the file where you want to define the variable use:

int my_global = 0; /* always good practice to initalize */

in other files (or a common header) use:

extern int my_global;

Now you can read or write my_global from any file where it is declared.

The header guard stuff is an attempt to move the definition and declaration into the same statement, at your level it is probably best that you get a handle on declaration vs definition before trying to play games like that.

OTHER TIPS

int j=6;int i=7;
char c='x';

You don't want these in a header file, as they're definitions. Put them in the C file instead, and just include the same header in both files (with the extern declarations of the variables).

As it stands, both of your source files are trying to define these variables, which is why you get the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top