简体   繁体   English

编译C文件的问题

[英]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...我的老师以一个 .h 文件和两个 .c 文件为例:它们是......

foo.c foo.c

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

foo.h foo.h

extern int foo(int);

use-foo.c使用-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.我希望有人能指导我完成这个,我不需要不同的解决方案,请帮助我处理这 3 个唯一的文件,因为老师的目的是这个。

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.只要确保你的所有文件都在同一个目录中,你从那个目录调用 gcc 并且 gcc 安装在你的系统上。

A couple more advices on including files, and cross-compiling : All your header files (like foo.h) should have include guards, like that关于包含文件和交叉编译的更多建议:所有头文件(如 foo.h)都应该包含保护,就像那样

#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.另一个建议是在你的 foo.c 代码中也包含 foo.h。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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