Your code is fine as it stands. I can give you an example of how multiple source files should be used in C and you can compare with what you have written.
Given a main.c
and a some_lib.c
containing func
, you need to define a some_lib.h
which defines the function prototype of func
defined in some_lib.c
.
main.c
:
#include <stdlib.h>
#include <stdio.h>
#include "some_lib.h"
/*
* This means main.c can expect the functions exported in some_lib.h
* to be exposed by some source it will later be 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 and %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 then be compiled with:
gcc main.c some_lib.c -o main
This will produce:
Received 100 and some_string
However, if you are indeed using a global variable, it is not even necessary to pass dir
at all. Consider this 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
is defined in here and is globally accessible/defined. All we need to do is make sure that some_lib.c
knows that it exists. The linker can then resolve this symbol during the linking stage. some_lib.h
needs to be defined as so:
#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>
/*
* The extern informs the compiler that there is a variable of type char array which
* is defined somewhere elsewhere but it doesn't know where. The linker will
* match this with the actual definition in main.c in the linking stage.
*/
extern char dir[];
void func(int x);
#endif
some_lib.c
can then use the globally defined variable as if it were scoped:
#include "some_lib.h"
void func(int x)
{
printf("Received %d and %s\n", x, dir);
}
Compiling and running this will produce the same output as the first example.