Skip to content

Instantly share code, notes, and snippets.

@laughingclouds
Last active April 29, 2022 06:43
Show Gist options
  • Save laughingclouds/0987ede002118f55907c23ef5cd54675 to your computer and use it in GitHub Desktop.
Save laughingclouds/0987ede002118f55907c23ef5cd54675 to your computer and use it in GitHub Desktop.
User defined header file example
#include <stdio.h>
#include "new.h"
int main() {
struct Student student1 = {
"Hemant", "CSE", 18, 0.5
};
printf("%i\n", add(2, 4));
printStudent(student1);
return 0;
}
#ifndef STUDENT
#define STUDENT
/*The structure Student*/
struct Student {
char name[50];
char major[50];
int age;
double gpa;
};
#endif
extern int add(int a, int b);
extern void printStudent(struct Student student);

Here, add() and printStudent() are user defined functins defined in file second.c.

We are using the functions defined in second.c in the file first.c.

For that, we use the header file new.h. It will contain declaration of add and printStudent, but the definition will be in second.c.

After defining the functions in new.h we include the header file in first.c.

For all of this to work, we will need to compile first.c and second.c together. This is because during compilation, the linker will link all the functions defined in new.h with where they are originally declared.

With the gcc compiler we can use the following command

gcc first.c second.c

Another way is to first only compile and assemble second.c and then compile the output together with first.c.

gcc -c second.c -o second; gcc first.c second

There are other ways to do it, but currently this is all I know.

#include <stdio.h>
#include "new.h"
/*Print the Student struct*/
void printStudent(struct Student student) {
printf("%s %s %i %0.2f", student.name, student.major, student.age, student.gpa);
}
/*Returns the sum of a and b*/
int add(int a, int b) {
return a + b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment