Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

c - Makefile include header

I am new to Linux programming I tried to compile a simple test construction. But I'm getting an error when compiling. Adding inc.c as well (in the app: line) doesn't work. How should I include the file correct?

Makefile:

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

Terminal:

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:
");
    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!");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must link against the compilation unit inc.o which you obtain by compiling inc.c.

In general that means that you must supply all object files that contain functions that are used in main.c (transitively). You can compile these with implicit rules of make, no need to specify extra rules.

You could say:

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

And make will know on its own how to compile inc.o from inc.c although it will not take inc.h into account when determining whether inc.o must be rebuilt. For that you would have to specify your own rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...