头文件(.text + 0x15):未定义引用

时间:2021-08-13 15:05:52

I write simple header file when I compile I get the error

我编译时编写简单的头文件我得到了错误

/tmp/ccOH3HcX.o: In function `main':
sample.c:(.text+0x15): undefined reference to `f'
collect2: error: ld returned 1 exit status

whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it :

要编译它:

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

2 个解决方案

#1


You need to include the object file whatever.o on the second gcc compilation line.

您需要在第二个gcc编译行中包含目标文件whatever.o。

A simple gcc whatever.c sample.c -o sample should do it

一个简单的gcc whatever.c sample.c -o sample应该这样做

#2


The compiler steps you gave only create object files, not an executable. I suppose you did something like

您只给出了创建对象文件的编译器步骤,而不是可执行文件。我想你做了类似的事情

gcc sample.c -o sample

afterwards and then got the error?

之后然后得到了错误?

You have to link the object files to get an executable, like so:

您必须链接目标文件以获取可执行文件,如下所示:

gcc whatever.o sample.o -o executable_file

#1


You need to include the object file whatever.o on the second gcc compilation line.

您需要在第二个gcc编译行中包含目标文件whatever.o。

A simple gcc whatever.c sample.c -o sample should do it

一个简单的gcc whatever.c sample.c -o sample应该这样做

#2


The compiler steps you gave only create object files, not an executable. I suppose you did something like

您只给出了创建对象文件的编译器步骤,而不是可执行文件。我想你做了类似的事情

gcc sample.c -o sample

afterwards and then got the error?

之后然后得到了错误?

You have to link the object files to get an executable, like so:

您必须链接目标文件以获取可执行文件,如下所示:

gcc whatever.o sample.o -o executable_file