passing a global variable in one C file to another -


let's have global variable

 char  dir[80];  /* declared , defined in file1.c  not exported using extern etc */ 

the dir variable name of directory created @ run time in program's main(). in file manipulate variable , pass function func defined in file2.c dir variable directory in functions create thier individual logs.

instead of passing variable n number of times each 1 of functions called func().i made global.

func(x,dir); /* x  local variable in function  */ 

/* in file2.c */

void func(int x,char *dir) {    /*use variable dir */ } 

the value of dir receive here not same in file1.c. why ? compiler: gcc on windows

your code fine stands. can give example of how multiple source files should used in c , can compare have written.

given main.c , some_lib.c containing func, need define some_lib.h defines function prototype of func defined in some_lib.c.

main.c:

#include <stdlib.h> #include <stdio.h> #include "some_lib.h" /*  * means main.c can expect functions exported in some_lib.h  * exposed source later linked against.  */  int main(void) {     char dir[] = "some_string";      func(100, dir);     return exit_success; } 

some_lib.c (contains definition of func):

#include "some_lib.h"  void func(int x, char * dir) {     printf("received %d , %s\n", x, dir); } 

some_lib.h (contains function prototype/declaration of exported functions of some_lib.c):

#ifndef some_lib_h #define some_lib_h #include <stdio.h>  void func(int x, char * dir);  #endif 

the above should compiled with:

gcc main.c some_lib.c -o main 

this produce:

received 100 , some_string 

however, if indeed using global variable, not necessary pass dir @ all. consider modified main.c:

#include <stdlib.h> #include <stdio.h> #include "some_lib.h"  char dir[] = "some_string";  int main(void) {     func(100);     return exit_success; } 

dir defined in here , globally accessible/defined. need make sure some_lib.c knows exists. linker can resolve symbol during linking stage. some_lib.h needs defined so:

#ifndef some_lib_h #define some_lib_h #include <stdio.h>  /*  * extern informs compiler there variable of type char array  * defined somewhere elsewhere doesn't know where. linker  * match actual definition in main.c in linking stage.  */ extern char dir[]; void func(int x);  #endif 

some_lib.c can use globally defined variable if scoped:

#include "some_lib.h"  void func(int x) {     printf("received %d , %s\n", x, dir); } 

compiling , running produce same output first example.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -