正确使用头文件 [英] Proper use of header files

查看:133
本文介绍了正确使用头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

未来与在main.c中未定义的引用错误这是因为我在这个时尚的几个文件:

Coming up with errors for undefined references in main.c. This is because I have several files in this fashion:

main.c
{
    #include "somefile.h"
    somfunct() <--- undefined reference error
}

somefile.h
{
    somefunct() declaration
    ...
}

somefile.c
{
    #include "somefile.h"
    somefunct() definition
    ...
}

我试图用正确的组织,我只使用声明的头文件,并在一个单独的文件中定义它们。分手了我的code后,我得到未定义的引用错误,因为有somefile.h和somefile.c之间没有联系。 虽然main.c中包括somefile.h头文件,没有什么somefile.h明确提到somefile.c ,所以我的功能只是部分定义。什么是采取这一问题的护理的正确方法?非常感谢。我希望这是明确的,让我知道,如果没有。

I am trying to use proper organization in that I use only declarations in the header files and define them in a separate file. After splitting up my code I get the undefined reference error because there is no link between somefile.h and somefile.c. Even though main.c includes the somefile.h header file, there is nothing in somefile.h that explicitly mentions somefile.c, so my functions are only partially defined. What is the proper way to take care of this problem? Many thanks. I hope this is clear let me know if not.

推荐答案

下面是你的目标一个完整的工作示例。

Here's a complete and working example of your goal.

#include "somefile.h"

int main() {
    somefunc();
    return 0;
}

somefile.h

#ifndef RHURAC_SOMEFILE_H
#define RHURAC_SOMEFILE_H

void somefunc();

#endif

somefile.c

#include <stdio.h>
#include "somefile.h"

void somefunc() {
    printf("hello\n");
}


的例子版本(GCC)

gcc main.c somefile.c -o main

输出

$ ./main 
hello

这篇关于正确使用头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆