nkeck72
nkeck72

Reputation: 3

Issues with .h files in C

I created a sample .h file in C and it didn't work, for some reason. The files are as follows:

header.c:

#include <stdio.h> 
#include "header.h"
int add(int a, int b) {
int tmp=a;
int i;
for(i=0, i==tmp, i++) {
b++;
}
return(b);
}

header.h:

#ifndef HEADER_H
#define HEADER_H

int add(int a, int b);
#endif

main.c:

#include <stdio.h>
#include "header.h"
int main(void) {
int foo=add(1, 2);
printf("%i \n", foo);
return(0);
}

When I try to compile main.c with make and gcc it says that add is undefined. Help!

Upvotes: 0

Views: 53

Answers (3)

P.P
P.P

Reputation: 121387

Including the header file only includes the function prototype. You need to link the actual definition of add() by compiling separate object files or you can compile them together in a single command line:

gcc -Wall -Wextra header.c main.c -o main

Perhaps, you may want to consider Makefiles for larger projects.

Your add() function has issues:

1) Semi-colons ; are used in for loops, not commas.
2) The condition should be i!=tmp for addition.

This:

for(i=0, i==tmp, i++) { .. }

should be

for(i=0; i!=tmp; i++) { .. }

Upvotes: 1

Jiminion
Jiminion

Reputation: 5168

You need to add header.c to the compile call. You can't just compile main.c.

Upvotes: 1

dbush
dbush

Reputation: 223739

You need to compile both main.c and header.c into the same executable:

all: main

main: main.o header.o
    gcc -o main main.o header.o

header.o: header.c header.h
    gcc -c header.c

main.o: main.c header.h
    gcc -c main.c

Or for a one-liner without a make file:

gcc -g -o main main.c header.c

Upvotes: 2

Related Questions