“未定义的引用"指的是:链接目标文件时出错 [英] "Undefined reference to" Error while linking object files

查看:1193
本文介绍了“未定义的引用"指的是:链接目标文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已通过多种方式提出,包括

I realize this question has been asked in a number of ways including this very comprehensive answer but I have looked at many and tried fixing my error to no avail.

我正在使用.cpp和.c文件来创建程序.我用g ++编译了所有文件,尽管它给了我许多与C语法有关的C ++错误,但似乎没有更多的链接错误.这是我使用的命令:

I am using .cpp and .c files to create a program. I compiled all files with g++, it seemed to have no more linking errors, though it gave me a bunch of C++ errors related to the C syntax. This was the command I used:

g++ -o program main.cpp /data/*.c -l[...libs]

main.cpp调用.c文件中的函数. 然后我明白,一个人不应该尝试使用一个编译器来编译.c和.cpp文件,而是要对一个使用gcc,对另一个使用g ++,然后再简单地链接目标文件.

The main.cpp calls functions in the .c files. I then understood that one should not try to compile both .c and .cpp files with one compiler, instead to use gcc for one, g++ for the other, and thereafter to simply link the object files.

所以我做到了(.c文件是库的一部分,并且已经有.o文件)

So I did this (the .c files are part of a library, and already have .o files)

g++ -c main.cpp
g++ -o program main.o /data/*.o -l[..libs]

但是在这里,我将从main.cpp调用到预编译的.c文件的函数中获得未定义的引用"错误,这是我以前没有得到的错误.

But then here I will get "undefined reference to" errors for functions called from main.cpp to the precompiled .c files, errors which I didn't get previously.

有人可以帮忙吗?还是我可能需要提供更多信息?

Could anyone help? Or do I maybe need to provide more information?

编辑(更深入的代码摘录,我已经尝试简化,否则将无法阅读,但是请告知我是否仍然需要添加内容,我将尝试删除不必要的代码):

EDIT (a more in depth excerpt of code, I've tried to simplify otherwise this will be impossible to read, but let me know if I still need to add stuff, I'll try to remove unnecessary code):

main.cpp:

#include "header.h"

int main(int argc, char** argv) {
    string s1 = argv[2];
    fn1(s1)
}

header.h

void fn1(string s1)

mycfile.c

mycfile.c

#include "header.h"

void fn1(string s1){
    fprintf(stdout, " you entered %s", s1);
    fflush(stdout);
}

答案:

@Smeehey帮助我找到了解决方案,实际上是我仍然在使用的.hpp文件中包含旧的标头.但是核心解决方案的确是使用外部C {}.

@Smeehey helped me figure out the solution, it was actually that I was still including the old headers in an .hpp file I was using. But the core solution was indeed to use the external C{}.

推荐答案

这很可能与C-vs-C ++链接有关.在您的main.cpp中,您可能会有类似的内容:

This is highly likely to do with C-vs-C++ linkage. In your main.cpp, you probably have something like this:

#include <data/header.h>

其中,header.h是指您的c库.替换如下:

where header.h refers to your c library. Replace it as follows:

extern "C" {
#include <data/header.h>
}

这告诉您的c ++编译器在从标头定义所需的符号时不要使用c ++样式的名称修饰,从而允许链接程序在c编译的.o文件中成功找到它们.

This tells your c++ compiler not to use c++-style name mangling when defining the required symbols from the header, allowing the linker to successfully find them in the c-compiled .o files.

这篇关于“未定义的引用"指的是:链接目标文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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