meta data for this page
  •  

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

courses:ct30a5002:multifiles [2013/09/23 18:42]
julaakko created
courses:ct30a5002:multifiles [2013/09/23 18:50] (current)
julaakko
Line 1: Line 1:
 +====== Using Multiple files ======
  
 +
 +Files:
 +  * main.c - main file, contains implementations of main() and run()-functions.
 +<code c main.c>
 +#include "​main.h"​
 +
 +int main(int argc, char *argv[])
 +{
 + ​printf("​Main\n"​);​
 +
 + ​run(argc);​
 +
 + ​return 0;
 +}
 +
 +void run(int _type)
 +{
 +  if(check(_type) < 0) printf("​Error\n"​);​
 +  else printf("​Success\n"​);​
 +}
 +</​code>​
 +
 +  * main.h - header for main.c, contains prototype for ''​run()''​-function.
 +
 +<code c main.h>
 +#include <​stdio.h>​
 +
 +void run();
 +</​code>​
 +
 +  * file.c - additional file, contains implementation of check()-function.
 +<code c file.c>
 +#include "​file.h"​
 +
 +int check(int _type)
 +{
 +  if(_type == RIGHT) return 1;
 +  else return -1;
 +}
 +</​code>​
 +
 +  * file.h - header for file.c, contains prototype for ''​check()''​-function.
 +<code c file.h>
 +#define RIGHT 0
 +
 +int check(int);
 +</​code>​
 +
 +
 +To use the function defined in file.h and implemented in file.c in the main.c following steps are needed:
 +  - Include the file.h in main.c (or in main.h)
 +    * main.c after modifications:<​code c main_mod.c>​
 +#include "​main.h"​
 +#include "​file.h
 +
 +int main(int argc, char *argv[])
 +{
 + ​printf("​Main\n"​);​
 +
 + ​run(argc);​
 +
 + ​return 0;
 +}
 +
 +void run(int _type)
 +{
 +  if(check(_type) < 0) printf("​Error\n"​);​
 +  else printf("​Success\n"​);​
 +}
 +</​code>​
 +    * After this the compiler and linker can find the function ''​check()''​ used in ''​run()''​ since it is defined in one of the headers included.
 +  - Add file.c into the Makefile of the application as source (remember to separate multiple files with spaces), in this case <​code>​SOURCES=main.c file.c</​code>​
 +
 +
 +----
 +[[courses:​ct30a5002:​start#​code_snippets|CT30A5002 - Games and Networking]]