0

I want to declare and define (with a default value) a variable in a .h file.

When I do that I get

/tmp/cc19EVVe.o:(.data+0x0): multiple definition of `car_name'
/tmp/cc3twlar.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status

How do I achieve my goal? Namely, to declare and define with default values a variable in a .h file and use that variable in multiple .c files?

Here is the A.h file

char * car_name = "Volkswagen";
void execute();

Here are the first file that uses the variable car_name defined in A.h: (The file is called execute.c)

#include "A.h"
#include <stdio.h>
#include <string.h>

void execute(){

    int len = sizeof(car_name) + 2;
    char car_name_with_new_line[len];
    strncat(car_name_with_new_line, car_name,  sizeof(car_name));
    strncat(car_name_with_new_line, "\n", 1);
    printf(car_name_with_new_line);

}

That's the other .c file: (It's called main.c)

#include "A.h"


int main(int argc, char ** argv){

    execute();
    return 0;

}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
Jenia Ivanov
  • 2,485
  • 3
  • 41
  • 69
  • 1
    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) – Retired Ninja Feb 24 '15 at 01:40

2 Answers2

4

The answer is simple: Define your variables in exactly one compilation unit (.c file). Declare them in the header file associated with that .c file.

foo.h

extern char *g_name;        // Declare that g_name exists

foo.c

#include "foo.h"
char *g_name;               // Define g_name in one place

static char *m_private;     // Private to foo.c, not "exported" via foo.h

main.c

#include "foo.h"

void somefunc(void)
{
    // use g_name
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
3

1) define the variable in a single file, do not add a static modifier

2) place an extern statement for that variable in the header file.

then only one instance of the variable exists anyone that includes the header file can access the variable.

Note: it is poor programming practice to have global variables.

Good programming practice is to write accessor functions and hide the variable within a file. similar to the following:

static int myVariable = 0;

void setMyVariable( int myVariableParm )
{   
    myVariable = myVariableParm;
}

int getMyVariable( void )
{
    return myVariable;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user3629249
  • 16,402
  • 1
  • 16
  • 17