在C语言编程,什么是'未定义reference`error,编译时? [英] In C programming, what is `undefined reference`error, when compiling?

查看:230
本文介绍了在C语言编程,什么是'未定义reference`error,编译时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个下面的程序我试图在Linux操作系统Ubuntu进行编译。

I have this following simple program I am trying to compile in linux ubuntu.

MAIN.C

Main.c:

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

int main()
{   
    struct Person1 p1 = Person1_Constructor(10, 1000);
}

Person.c

Person.c:

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

struct Person1 Person1_Constructor(const int age, const int salary)
{
    struct Person1 p;
    p.age = age;
    p.salary = salary;
    return p;
};

Person.h

Person.h:

struct Person1
{
    int age, salary;
};
struct Person1 Person1_Constructor(const int age, const int salary);

为什么会出现以下的错误

/tmp/ccCGDJ1k.o: In function `main':
Main.c:(.text+0x2a): undefined reference to `Person1_Constructor'
collect2: error: ld returned 1 exit status

我使用的gcc -o main.c中主要进行编译。

推荐答案

当你链接,你需要给双方main.o中和Person.o作为输入的程序。

When you link the program you need to give both Main.o and Person.o as inputs.

构建通常是在两个步骤(1)汇编和(2)连接完成。
要编译你的源代码做的:

Build usually is done in two steps (1) compilation and (2) linking. To compile your sources do:

$ gcc -c -o Main.o Main.c
$ gcc -c -o Person.o Person.o

然后将生成的对象文件必须链接到一个可执行文件:

Then the resulting object files must be linked into a single executable:

$ gcc -o Main Main.o Person.o

对于小型项目,几个编译单元像你这样,既一步可以在一个做的gcc 调用:

$ gcc -o Main Main.c Person.c

必须给予这两个文件,​​因为 Person.c 一些符号是由 MAIN.C 使用。

有关更大的项目,这两个步骤可以让编译可执行文件的生成过程中仅发生了什么变化。通常这是通过一个Makefile完成。

For bigger projects, the two step process allows to compile only what changed during the generation of the executable. Usually this is done through a Makefile.

这篇关于在C语言编程,什么是'未定义reference`error,编译时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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