简体   繁体   English

C 中的每个 function 是否应该有自己的.c 文件? 或者我可以将我程序的所有功能放在一个.c 文件中吗?

[英]Should every function in C have its own .c file ? or can i put all the functions of my program in one .c file?

I'm new to C programming and i just started studying functions.我是 C 编程的新手,我刚开始学习函数。 Should i put each function in a.c and.h file, or can i put all of the functions and headers in one.c and.h file?我应该将每个 function 放在 a.c 和 .h 文件中,还是可以将所有函数和头文件放在一个.Z4A8A08F09D37B73795649038408B5F3Z 和.h 文件中? Thank you.谢谢你。

Determining where to put different parts of your code is something that comes with both your personal and the programming language experience.确定将代码的不同部分放在哪里是您的个人和编程语言经验所附带的。 Considering your mention that you're currently learning about functions, let me go over a couple main factors in deciding where to put your functions.考虑到您提到您目前正在学习函数,让我 go 讨论决定将函数放置在何处的几个主要因素。

Prototypes原型


When writing your code, before you can use a variable, you need to declare it first.编写代码时,在使用变量之前,需要先声明它。 The same goes for functions.函数也是如此。 The first, simple approach is defining a function before you use it.第一种简单的方法是在使用之前定义一个 function。

int add(int a, int b) {
    return a + b;
}

int main(void) {
    int result = add(10, 8);
    return 0;
}

Here I defined a function add() and called in the function main() .这里我定义了一个 function add()并在 function main()中调用。 This piece of code will simply compile and run.这段代码将简单地编译和运行。 However, what if I placed my definition of the add() function below the main() function?但是,如果我将add() function 的定义放在main() function 下方怎么办?

int main(void) {
    int result = add(10, 8);
    return 0;
}

int add(int a, int b) {
    return a + b;
}

This piece of code will result into a compilation error.这段代码会导致编译错误。 The compiler doesn't know which add() function I'm calling in the main() function, because no add() function has been defined yet.编译器不知道我在main() function 中调用了哪个add() ) function,因为尚未定义add() function。 Sometimes you can solve this problem by simply re-arranging the code.有时你可以通过简单地重新排列代码来解决这个问题。 Other times that is not possible and that's why prototyping comes into play.其他时候这是不可能的,这就是原型设计发挥作用的原因。

int add(int a, int b);

int main(void) {
    int result = add(10, 8);
    return 0;
}

int add(int a, int b) {
    return a + b;
}

This tells the compiler there is a function add() accepting two int parameters, that will be defined later in the code.这告诉编译器有一个 function add()接受两个int参数,稍后将在代码中定义。 The compiler is satisfied and indeed - this piece of code compiles without an issue once again.编译器确实很满意 - 这段代码再次编译没有问题。

The #include directive #include指令


Including headers in C is a bit troublesome.在 C 中包含表头有点麻烦。 It is the method of including the definitions in header files inside your .c files, and it's done in the simplest way imaginable - every #include <my_header.h> directive in your C code gets simply replaced with all contents of the my_header.h file before the compilation. It is the method of including the definitions in header files inside your .c files, and it's done in the simplest way imaginable - every #include <my_header.h> directive in your C code gets simply replaced with all contents of the my_header.h编译的文件。 For example imagine the following files:例如想象以下文件:

my_header.h

// Hello, I am the my_header.h file
// I currently have no definitions

my_program.c

#include "my_header.h"

int main(void) {
    // Do nothing
    return 0;
}

If I compile just my_program.c , the preprocessor will examine the file before the compiler does.如果我只编译my_program.c ,预处理器将在编译器之前检查文件。 It will find an #include directive, look for a file named my_header.h , find it and copy its contents into the .c file simply like this:它将找到一个#include指令,查找名为my_header.h的文件,找到它并将其内容复制到.c文件中,如下所示:

// Hello, I am the my_header.h file
// I currently have no definitions

int main(void) {
    // Do nothing
    return 0;
}

Then the resulting file will be given to the compiler.然后将生成的文件提供给编译器。

While this approach is incredibly simple and easy to implement, it makes C very prone to errors and hard to maintain, unless great care is taken.虽然这种方法非常简单且易于实施,但它使 C 非常容易出错且难以维护,除非非常小心。 This is for example the reason include guards exist.例如,这就是包括警卫存在的原因。 Imagine you include two files in your main file.假设您在主文件中包含两个文件。 Now both of those two files include one, third file.现在这两个文件都包括一个,第三个文件。 After all the replacements done, you'll end up having the third file pasted twice inside your code, which will result in naming conflicts during a compilation.完成所有替换后,您最终会在代码中粘贴两次第三个文件,这将导致编译期间的命名冲突。

This also means you technically can put any sort of code inside the header files.这也意味着您在技术上可以将任何类型的代码放入 header 文件中。 However, in my whole career, I was met with only one case when such code was acceptable (in a bare metal embedded system program), so I can't stress this out enough - unless you really, really know what you're doing, never put anything other than function prototypes, variable declarations, includes and macros inside a header file.然而,在我的整个职业生涯中,我只遇到过这样一个代码是可以接受的情况(在裸机嵌入式系统程序中),所以我不能强调这一点——除非你真的、真的知道你在做什么,除了 function 原型、变量声明、包含和宏之外,切勿将任何其他内容放入 header 文件中。 Doing otherwise is the easiest way to have your code break in the most inexplicable of ways.不这样做是以最莫名其妙的方式破坏代码的最简单方法。

The conclusion结论


The style I've seen the most often (and also personally follow) is separating sets of functions with similar functionalities into individual .c files.我最常看到的(也是个人遵循的)风格是将具有相似功能的函数集分成单独.c文件。 This .c file contains nothing, but function definitions (ie the code) and a single #include directive of the header file this .c file is associated with. This .c file contains nothing, but function definitions (ie the code) and a single #include directive of the header file this .c file is associated with. This keeps all the functions in a separate translation unit .这将所有功能保存在一个单独的翻译单元中。

The header file with include guards (isn't needed when you don't include the file more than once anywhere, but it's a good habit to get used to) contains all the required #include directives of system libraries, other header files in your project and function prototypes of every function in the respective .c file.带有包含保护的 header 文件(当您在任何地方不多次包含该文件时不需要,但这是一个习惯的好习惯)包含系统库的所有必需的#include指令,您的其他 header 文件在相应的.c文件中的每个 function 的项目和 function 原型。 Whenever you then need to use those functions elsewhere, include this header file in any other header file.每当您需要在其他地方使用这些功能时,请将此 header 文件包含在任何其他 header 文件中。 System libraries are generally included using <> while your own files are included using "" .系统库通常使用<>包含,而您自己的文件则使用""包含。

As remarked by other answers, the .c file containing the main function can often exists without the respective header file.正如其他答案所指出的那样,包含主 function 的.c文件通常可以在没有相应的 header 文件的情况下存在。 All other .c files should have a header file associated.所有其他.c文件应具有关联的 header 文件。 This is mostly in line with the Google's C++ Style Guide .这主要符合Google 的 C++ 样式指南

An example一个例子


For any smaller project, you most likely won't need more than just two files.对于任何较小的项目,您很可能只需要两个文件。 Take these as an example:以这些为例:

main.h

#ifndef _MAIN_H_
#define _MAIN_H_

#include <stdio.h>
// any other includes

int add(int a, int b);
int sub(int a, int b);

int main(int argc, char *argv[]);

#endif // _MAIN_H_

main.c

#include "main.h"

int main(int argc, char *argv[])
{
    int first = 10;
    int second = 8;
    int third, fourth;

    third = add(first, second);
    fourth = sub(third, first);

    return 0;
}

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

If you were to add more mathematical functions, say mul() and div() , it'd be appropriate to take them all out of the main.c file and create a new pair of files - something along the way of my_math.c and my_math.h , following the same rules as the rest of your project.如果您要添加更多数学函数,例如mul()div() ,最好将它们全部从main.c文件中取出并创建一新文件 - 类似于my_math.cmy_math.h ,遵循与项目的 rest 相同的规则。 Then, to call the mul() function in your main function, you'd need to #include my_math.h inside main.h .然后,要在主 function 中调用mul() function,您需要在 main.h 中#include my_math.h main.h


A lot of this comes with the experience.其中很多都来自经验。 Feel free to explore other styles and try out what works the best for you.随意探索其他 styles 并尝试最适合您的。 The most important part in all of this is staying consistent .所有这一切中最重要的部分是保持一致 Pick a style and stick to it.选择一种风格并坚持下去。 Best of luck in your studies!祝你学业好运!

Should every function (definition) in C have its own .c file? C 中的每个 function(定义)是否应该有自己的.c文件?

No. should not, but can .应该,但可以 It's a matter of coding-style, but it's not the preferred way to do so and unusual.这是编码风格的问题,但这不是这样做的首选方式并且不寻常。 It increases compilation and linking time.它增加了编译和链接时间。


Or can I put all the function (definitions) of my program in one .c file?或者我可以将我程序的所有 function(定义)放在一个.c文件中吗?

Yes, you can .是的,你可以 Also again, matter of one's own coding-style.同样,关于自己的编码风格。

If you got a lot or several functions in your code, you can also group the function definitions into own .c files and then link the files when invoking the compiler.如果您的代码中有很多或多个函数,您还可以将 function 定义分组到自己的.c文件中,然后在调用编译器时链接这些文件。

This way you keep clarity.这样你就可以保持清晰。

One way is also to keep all function definitions in a separate .c file, apart from main.c , which contains the main function. One way is also to keep all function definitions in a separate .c file, apart from main.c , which contains the main function.


Should I put each function in a .c and .h file?我应该将每个 function 放在.c.h文件中吗?

Function definitions can't be placed inside of .h files. Function 定义不能放在.h文件中。

.h consist only of function and other variable declarations, as well as macro definitions. .h仅包含 function 和其他变量声明以及宏定义。

Function definitions need to be placed in .c files. Function 定义需要放在.c文件中。

If you mean to place each function definition into an own .c file and each function declaration in an own .h , that definitely does not need to be either.如果您打算将每个 function 定义放入自己的.c文件中,并且每个 function 声明都不需要在自己的.h中声明。

It even would confuse you all the way up.它甚至会让你一直困惑。

You actually can do so, but it is definitely not recommended.您实际上可以这样做,但绝对不建议这样做。


Or can I put all of the functions and headers in one .c and .h file?或者我可以将所有函数和标题放在一个.c.h文件中吗?

Again here you can't put function definitions in an .h file.同样在这里,您不能将 function 定义放在.h文件中。

But you can pack all function definitions in one .c file and all function declarations in one .h file.但是您可以将所有 function 定义打包在一个.c文件中,并将所有 function 声明打包在一个.h文件中。

No. There is no need to do it at all.不,根本没有必要这样做。 That would be affect your performance really badly.那会严重影响你的表现。

Usually we only tend to create new files.h to store functions/methods that we want to use repeatedly in other projects or programs I guess.通常我们只倾向于创建新的 files.h 来存储我们想在其他项目或程序中重复使用的函数/方法,我猜。

Your program should be as follows:您的程序应如下所示:

Let's call this prog1.c我们称之为 prog1.c

#include <only libs that you need>

    void functionA (parameterType parameter){
        //Whatever your function needs to do
    }
    int main(){
       //this is your main function and where the program will start working.
       functionA(parameters) /*Here is how you call functionA if it's void giving it's needed parameters.*/
    }

Later on, with more knowledge you'll learn when you need to store or not the functions in others files to learn and keep it organized.稍后,当您需要存储或不存储其他文件中的功能以学习和保持组织时,您将学习更多知识。 There's no need for that now.现在没必要了。 You should focus the most on learning how they work and communicate with each other.您应该最专注于了解它们如何工作和相互交流。

If you need to use functionA in other file, well then you will just need to include that.c file, like this:如果您需要在其他文件中使用 functionA,那么您只需要包含 that.c 文件,如下所示:

In prog2.c you start it by calling out在 prog2.c 中,您可以通过调用来启动它

#include "prog1.c"

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

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