The question may be very basic but I am not getting clue anyways …
I have two files …
and I am mentioning what I want to do .
file 1
...
j = data->alloc_len;
...
file 2
...
for(i=0;i<j;i++)
...
Its clear from above I want to assign value to a variable in one file and want to use that value in other file.
I tried #include "file1.c" in file2.c but it is giving lot of re-declaration errors.
I tried creating a seperate header file which only have one line int j and then included it in both files using extern but no benefit again.Although I think header files are meant for where i can create and assign a value to a variable in one file and then this value can be propogated to all other files by including this one.
May be I am wrong but I need it soon so please help me …Thnx in advance.
Limitation –
The value can be assigned only through file1.c because data structure is declared and defined here only.I can not provide a value to variable j in a header file .
EDIT :
Although I mentioned but I think I could not clear my question.I have tried using it header files.
For debugging purpose I tried this ..
sample.h
extern int j;
file1.c
#include "sample.h"
int j=245;
file2.c
#include "sample.h"
printf("%d",j);
but its getting error .
Error I am getting is :
Couldn't open module sample.so, tried:
sample.so: cannot open shared object file: No such file or directory
./sample.so.so: cannot open shared object file: No such file or directory
/usr/local/lib/sendip/sample.so.so:
cannot open shared object file: No such file or
directory
/usr/local/lib/sendip/sample.so: undefined symbol: j
*none of the file contains main function actually *
Actually it is a very large project and I am using Makefile and all files will be linked at run time.
In short,the execution could be understood as there is a main.c file which contains main which in turns call file1.c and which in turn calls file2.c
About descriptive names I would say they are just for showing here otherwise I am already using descriptive name.
You could put this in a header file:
and only declare the “real”
jin file1.c. If file2.c includes that header, then it can use variablej.But, use descriptive variable names a the very least for globals. And you should avoid globals as much as you can, they are a liability in the long term, IMO.
(You could consider something like making a function in
file1.cthat returns that value. This has the advantage of assuring thatjis controlled infile1.c, and only read in other places, limiting the complexity of understanding who “owns” that variable.)