包含头文件时未定义的引用 [英] undefined reference when including a header file

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

问题描述

包含头文件时出现错误,但如果包含源文件则没有错误.

I get an error when I include a header file, but not if I include the source file instead.

该函数在源文件中的定义如下:

The function is defined in the source file like this:

/* in User.c */

struct User {
    const char* name;
};

struct User* addedUser(const char* name) {
    struct User* user = malloc(sizeof(struct User));
    user->name = name;
     return user;
}

并以此方式使用:

/* in main.c */

int test_addedUser() {
    char* newName = "Fooface";
    struct User* newUser = addedUser(newName);
    assert(!strcmp(newName, newUser->name));
    return 0;
}

这很好.当我#include"User.c"时,我可以毫无问题地调用test_addUser.

This works great. I am able to call test_addUser without a problem when I #include "User.c".

但是,我想改为#include"User.h",它位于同一目录中:

However, I would like to #include "User.h" instead, which is located in the same directory:

/* in User.h */

struct User {
    const char* name;
};

struct User* addedUser(const char*);

但是,如果我#include"User.h"而不是User.c,则会出现错误:

But, if I #include "User.h" instead of User.c, I get an error:

CMakeFiles/run_tests.dir/src/tests.c.o: In function `test_addedUser':
/home/rid/port/src/tests.c:(.text+0x4eb): undefined reference to `addedUser'

令我感到奇怪的是,该引用在包含源文件User.c时工作正常,但无法协调User.h.

It seems strange to me that the reference works just fine when including the source file User.c but it is unable to reconcile User.h.

为什么会这样?

推荐答案

#include 意味着将包含的文件复制到源文件中.因此,当您包含.c文件时,该函数的代码就在这里并且可以正常工作.如果仅包含头文件,则很好的感谢是您的函数可以相互了解,至少它们现在已经存在,但是它们需要它们的代码一起工作,所以您现在需要将两个文件一起编译.逐个.也许您是自己编译的:

#include means that the file included is copied into the source file. So when you include your .c file, the function's code is here and it works. If you include only the header file, it's good thanks to that your functions will know each other, at least they will now they exist but they need their code to work together, so you need now to compile your two files.c together, not one by one. Maybe you're compiling by yourself :

gcc file1.c file2.c

或者使用IDE,您必须调整编译选项.如果要分别编译C文件,则必须将它们编译为目标文件(带有gcc的-c选项),然后链接它们.

Or with an IDE, you have to adjust the compiling options. If you want to compile the C files separatly, you have to compile them in object files (-c option with gcc), then link them.

这篇关于包含头文件时未定义的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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