You can make two files: one with the main function, and the other with the rest.
If your function in another file uses a global variable from another module / file, you need to add "extern" before declaring the global variable in the module along with the function definition. This tells the compiler that you are accessing a global variable from another file.
The following is an example that defines the global variable "x" and calls the function "myfunction" in the file main.c. "Myfunction" is defined in the functions.c file. "X" also needs to be declared in the functions.c file, but since it will access "x" from another file, it must be "extern" before it. "myfunction" takes an external global variable "x", incrementing it by one and prints it. Consider the following code:
main.c will look something like this:
#include <stdio.h> #include "functions.c" int x = 1; int main() { myfunction(); printf("The value of x in main is: %d\n", x); return(0); }
functions.c will look something like this:
#include <stdio.h> extern int x; void myfunction(void) { x++; printf("The value of x in myfunction is: %d\n",x); }
Note that main.c uses "int x;" declare x, while functions.c uses "extern int x" to declare x.
To compile the code, make sure that both files are in the same folder, and compile as if you had only one file. For example, if you use gcc on linux and gcc, your command line input would look like this:
gcc main.c -o main ./main
The first line compiles the code, and the second line runs it. The output should look like this:
The x value in myfunction is: 2 The x value in main is: 2
Note that the value of "x" also changes basically, since "x" is a global variable.