Skip to content

Instantly share code, notes, and snippets.

@paulbuis
Last active August 29, 2015 14:28
Show Gist options
  • Save paulbuis/92549ba717c77bfdea97 to your computer and use it in GitHub Desktop.
Save paulbuis/92549ba717c77bfdea97 to your computer and use it in GitHub Desktop.
Compile & Link: Calling C from C

The hello.h header file contains function prototypes that serve as declarations of the functions.

The hello.c file contains definitions of the functions after a preprocessor directive to include the contents of the header file. This ensures that the definitions are consistent with the declarations. Note the name of the header file is in quotes, indicating the header file should be looked for in the project source directory. The name of the standard I/O header is enclosed in angle brackets, indicating it should be looked for in the system header directory.

The main.c file also includes the hello.h header so that the use of the function hello() can be type-checked against the prototype. main() returns 0, indicating success, rather than an error code. The process that invoked fork() to create the process that called main, will be able to check this status result by invoking some variant of the wait() system call. The formal arguments to main() allow main() to access command line arguments. argc is the number of comand line arguments. argv is an array of strings providing access to the command line.

#include <stdio.h>
#include "hello.h"
void hello(int repeatCount) {
int i;
for (i = 0; i < repeatCount; i++) {
printf("hello from C\n");
}
}
void hello_(int *repeatCount) {
int i;
for (i = 0; i < *repeatCount; i++) {
printf("hello from C\n");
}
}
void hello(int repeatCount);
void hello_(int *repeatCount);
#include "hello.h"
int main(int argc, char** argv) {
hello(3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment