【问题标题】:Makefile include headerMakefile 包含头文件
【发布时间】:2013-03-15 18:58:59
【问题描述】:

我是 Linux 编程的新手,我尝试编译一个简单的测试结构。但是编译时出现错误。添加 inc.c (在应用程序:行中)也不起作用。我应该如何正确地包含文件?

生成文件:

app: main.c inc.h
    cc -o app main.c

终端:

make
cc -o app main.c
/tmp/ccGgdRNy.o: In function `main':
main.c:(.text+0x14): undefined reference to `test'
collect2: error: ld returned 1 exit status
make: *** [app] Error 1

main.c:

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

int main()
{
    printf("Kijken of deze **** werkt:\n");
    test();

    getchar();
    return 0;
}

inc.h

#ifndef INCLUDE_H

#define INCLUDE_H

void test();

#endif

inc.c

#include <stdio.h>

void test()
{
    printf("Blijkbaar wel!");
}

【问题讨论】:

    标签: c makefile


    【解决方案1】:

    你必须链接到你通过编译inc.c获得的编译单元inc.o。

    一般来说,这意味着您必须提供所有包含在main.c 中使用的函数的目标文件(可传递)。您可以使用make 的隐式规则编译这些,无需指定额外的规则。

    你可以说:

    app: main.c inc.o inc.h
        cc -o app inc.o main.c
    

    并且make 将自己知道如何从inc.c 编译inc.o,尽管在确定是否必须重建inc.o 时,它不会考虑inc.h。为此,您将必须指定自己的规则。

    【讨论】:

      【解决方案2】:

      你没有编译inc.c文件

      app: main.c inc.h
          cc -o app main.c inc.c
      

      【讨论】:

        【解决方案3】:

        您还需要编译inc.c。一种合适的方法(更好地扩展到更大的应用程序)是将 Makefile 拆分为不同的目标。这个想法是:每个目标文件都有一个目标,然后是最终二进制文件的一个目标。要编译目标文件,请使用 -c 参数。

        app: main.o inc.o
            cc -o app main.o inc.o
        
        main.o: main.c inc.h
            cc -c main.c
        
        inc.o: inc.c inc.h
            cc -c inc.c
        

        【讨论】:

        • 为什么要把头文件放在cc -c main.c inc.h和cc -c inc.c inc.h里?
        猜你喜欢
        • 2012-07-06
        • 1970-01-01
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2016-04-13
        • 2016-10-15
        相关资源
        最近更新 更多