链接静态C库时未定义的引用 [英] Undefined reference while linking static C library

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

问题描述

在我的最新项目中,我遇到一个奇怪的问题,即对共享库方法的未定义引用.我在SO上搜索,但我所能找到的要么与C ++有关(外部"C"),要么没有帮助.

In my latest project I am encountering a strange issue regarding an undefined reference to a method of a shared library. I searched on SO but all I could find was either C++ related (extern "C") or not really helping.

有问题的库是我的libosm分支,它使用protobuf生成用于二进制格式(.osm.pbf)的OpenStreetMap数据.有问题的函数是osmpbf__blob__unpack,但这只是我最终使用的第一个函数,因此我怀疑它是一个普遍的问题.

The library in question is my fork of libosm which uses protobuf to generate de-/serialization code for OpenStreetMap data in its binary format (.osm.pbf). The function in question is osmpbf__blob__unpack but that is just the first I end up using so I suspect its a general problem.

我用nm检查了生成的libosm.a,并且该方法在那里并导出了,但是由于某种原因在链接时找不到它.以下是我目前的标志.我尝试更改顺序,甚至两次都更改了所有库(如另一个线程中所建议),但是我总是以未定义的引用结尾.

I inspected the resulting libosm.a with nm and the method is there and exported but for some reason it is not found while linking. Below are my current flags. I tried changing the order and even including all libraries twice (as suggested in another thread) but I always end up with the undefined reference.

CFLAGS      = -v -std=c99 -O3 -Wall -Wextra -pedantic
LIBFLAGS    = -losmpbf -lprotobuf-c -lz -lpthread

此刻,我对可能的错误感到很迷惑,但我认为这可能是一个较小的一般性错误.自从我使用C.已经有一段时间了. 任何帮助将不胜感激.

At the moment I am quite lost on what the error could be, but I think it might be a minor general error. It has been a while since I used C.. Any help would be appreciated.

干杯, 弗洛里安

这是我完整的Makefile.我只是为变量LIBFLAGS命名,因为我使用了自己的小规则,但是对于这种简单情况,似乎应该使用LDLIBS和内置规则.

Here is my complete Makefile. I just made up the name for the variable LIBFLAGS since I use my own little rule but it seems like I should use LDLIBS and the builtin rules for this simple case.

CC          = gcc
CFLAGS      = -v -std=c99 -O3 -Wall -Wextra -pedantic
LIBFLAGS    = -losmpbf -lprotobuf-c -lz -lpthread

all: main.x

main.x: main.c
    $(CC) $(CFLAGS) $(LIBFLAGS) main.c -o main.x

clean:
    rm -rf *.o main.x

推荐答案

问题是链接器(gcc)与大多数链接器一样,从左到右处理参数.因此该链接可以看到这些库,但是没有待处理的未解决的引用,因此没有任何反应.

The problem is the linker (gcc), like most linkers, processes the parameters from left to right. so the link sees the libraries, but there is no unresolved references to be handled, so nothing happens.

解决方法是将库放在行的最后,而不是放在CFLAGS之后.

The fix is to place the libraries last on the line rather than just after the CFLAGS.

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

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