简体   繁体   中英

Problems in compiling C files

I have these three files which I'm trying to link together. It's a didactic example, I tried different combinations compiling the three files but I have no clue what' s wrong. Even if something with this trivial code is wrong.

What I'm trying to understand is how to separate in different files the declaration of a function in order to include it from an header file in the main one. Or at least this is what I figured out. My teacher set the example in order to have an .h file and two .c files: Here they are...

foo.c

int foo(int x){
return x==42 ? 1 : 0;
}

foo.h

extern int foo(int);

use-foo.c

#include <stdio.h>
#include "foo.h"
int main(){
printf("foo(42) == %d \n", foo(42));
getchar();
return 0;
}

I hope someone can guide my through this, I don't need a different solution , please help me with these 3 only files because the aim of the teacher was this.

You can compile it with the command :

gcc -o use-foo use-foo.c foo.c

Then you'll be able to run it with the command :

./use-foo

Just be sure that all your files are in the same directory, that you call gcc from that directory and that gcc is installed on your system.

A couple more advices on including files, and cross-compiling : All your header files (like foo.h) should have include guards, like that

#ifndef __FOO__
#define __FOO__

int foo (int);

#endif

that'll prevent the compiler from adding your header file more than once in your code.

Another advice would be to include foo.h in your foo.c code as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM