Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a variable in a one C file from another?

Tags:

c

variables

file

I have two C files. I want to declare a variable in one, then be able to access it from another C file. My definition of the example string might not be perfect, but you get the idea.

//file1.c

char *hello="hello";

//file2.c

printf("%s",hello);
like image 761
Sam H Avatar asked Dec 02 '10 22:12

Sam H


2 Answers

// file1.h
#ifndef FILE1_H
#define FILE1_H
extern char* hello;

#endif


// file1.c
// as before


// file2.c
#include "file1.h"
// the rest as before
like image 125
Karl Knechtel Avatar answered Oct 20 '22 06:10

Karl Knechtel


*hello in file1.c must be declarated global and extern in file2.c must be global too (not inside function)

//file2.c
extern char *hello;

... function()
{
printf(...)
}
like image 28
Svisstack Avatar answered Oct 20 '22 07:10

Svisstack