Sam H
Sam H

Reputation: 976

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

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);

Upvotes: 9

Views: 33855

Answers (6)

MdAshiff
MdAshiff

Reputation: 146

file_2.c

#include<stdio.h>

int count;
void extern_function();

void main()
{
count = 5;
extern_function();

}

file_3.c

#include<stdio.h>

void extern_function()
{

extern int count;   
printf("the value from the external file is %d",count);

}

Now run the code

    $gcc file_2.c file_3.c -o test
    $./test

It works!!

Upvotes: 0

mohsen
mohsen

Reputation: 21

file1.c

int temp1=25;
int main()
{
.
. 
}

file2.c

 extern int temp1;
 func1();
 func2(temp1);

temp1 is defined in file1.c .when you want to use it in file2.c you must write extern int temp1; you must do it in each file which you want to use this variable

Upvotes: 2

c.pyth.user
c.pyth.user

Reputation: 31

this works

t.c

#include <stdio.h>

int main(void)
{
    extern int d;

    printf("%d" "\n", d);
    return 0;
}

h.c

int d = 1;

output

[guest@localhost tests]$ .ansi t.c h.c -o t
[guest@localhost tests]$ ./t
1
[guest@localhost ~]$ alias .ansi
alias .ansi='cc -ansi -pedantic -Wall'
[guest@localhost ~]$

Upvotes: 2

D.C.
D.C.

Reputation: 15588

What you have would work. What you want to research is "linkage" in C. Basically objects not within a function or marked as static are extern (think global). What you need to do in this case is notify the compiler that there is in fact a variable called hello defined elsewhere. You do this by adding the following line to file2.c

extern char* hello;

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61526

// 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

Upvotes: 9

Svisstack
Svisstack

Reputation: 16616

*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(...)
}

Upvotes: 4

Related Questions