2

Hi I just wondering how to Share global variable between .c file.
I try to add follow code, but still get error.

test.c file

#include <stdio.h>

int max = 50;
int main() 
{
  printf("max %d", max); // result max 50
}

pass.h

extern int max;

passed.c

#include <stdio.h>
#include "pass.h"

max;

int main()
{    
    printf("pass %d \n", max);

    return 0;
}

But when I compile passed.c I get follow error

Undefined symbols for architecture x86_64:
"_max", referenced from:
  _main in passed-iOMugx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Can anyone help? Thank you so much.

laalto
  • 150,114
  • 66
  • 286
  • 303
Pakaphol Buathon
  • 188
  • 3
  • 18
  • Do you really mean to have two main() functions? – Charlie Burns Oct 16 '13 at 04:26
  • Why do you have two main functions? Are they separate programs or are they meant to be linked together into one program? If they are being linked together in one program it shouldn't have complained about max - it should have complained about duplicate main functions. – Jerry Jeremiah Oct 16 '13 at 04:29
  • Yes, I know it might impossible to do – Pakaphol Buathon Oct 16 '13 at 04:30
  • possible duplicate of [How do I share variables between different .c files?](http://stackoverflow.com/questions/1045501/how-do-i-share-variables-between-different-c-files) – 7hi4g0 Jun 03 '15 at 06:16

2 Answers2

4

You can declare the variable in a header file, e.g. let's say in declareGlobal.h-

//declareGlobal.h
extern int max; 

Then you should define the variable in one and only file, e.g. let's say, test.c. Remember to include the header file where the variable was declared, e.g. in this case, declareGlobal.c

//test.c
#include "declareGlobal.h"
int max = 50;

You can then use this variable in any file- just remember to include the header file where it's declared (i.e. declareGlobal.c), for example, if you want to use it in passed.c, you can do the following:

//passed.c
#include <stdio.h>
#include "declareGlobal.h"
#include "test.c"
int main()
{
printf("pass %d \n", max);
return 0;
}
Subzero
  • 841
  • 6
  • 20
2

The problem is that you have two programs, and data (like variables) can not be shared that simply between programs.

You might want to read about shared memory and other inter-process communication methods.


If on the other hand you only want to have one program, and use a variable defined in another file, you still are doing it wrong. You can only have one main function in a single program, so remove the main function from one of the source files. Also in pass.c the expression max; does nothing and you don't need it.

Then pass both files when compiling, like

$ clang -Wall -g test.c pass.c -o my_program

After the above command, you will (hopefully) have an executable program named my_program.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621