3

当我尝试编译我的单元测试文件时,我得到“未定义的对‘dlsym’的引用”错误。我在 Unix 系统(我在 Ubuntu 12.04 上)上读到了,将 -ldl 添加到编译器工作中,但我尝试使用 Zed 的 Shaw Makefile,但仍然没有任何反应。这是代码:

CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LIBS=-ldl $(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/**/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/libex29.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

# The Target Build
all: $(TARGET) $(SO_TARGET) tests

dev:    CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev:    all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
    ar rcs $@ $(OBJECTS)
    ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)

build:
    @mkdir -p build
    @mkdir -p bin

# The Unit Tests
.PHONY: tests
tests: CFLAGS += $(TARGET) 
tests: $(TESTS)
    sh ./tests/runtests.sh

valgrind:
    VALGRIND="valgrind --log-file=/tmp/valgrind-%p.log" $(MAKE)

# The Cleaner
clean:
    rm -rf build $(OBJECTS) $(TESTS)
    rm -f tests/tests.log
    find . -name "*.gc*" -exec rm {} \;
    rm -rf `find . -name "*.dSYM" -print`

# The Install
install: all
    install -d $(DESTDIR)/$(PREFIX)/lib/
    install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

记录错误:

michal@ubuntu:~/Documents/projectsc/c-skeleton$ make
ar rcs build/libex29.a src/libex29.o
ranlib build/libex29.a
cc -shared -o build/libex29.so src/libex29.o
cc -g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG -LIBS  build/libex29.a     tests/libex29_tests.c   -o tests/libex29_tests
tests/libex29_tests.c: In function ‘main’:
tests/libex29_tests.c:66:1: warning: parameter ‘argc’ set but not used [-Wunused-but-set-parameter]
/tmp/ccRX6ddf.o: In function `check_function':
/home/michal/Documents/projectsc/c-skeleton/tests/libex29_tests.c:10: undefined reference to `dlsym'
/home/michal/Documents/projectsc/c-skeleton/tests/libex29_tests.c:11: undefined reference to `dlerror'
/tmp/ccRX6ddf.o: In function `test_dlopen':
/home/michal/Documents/projectsc/c-skeleton/tests/libex29_tests.c:24: undefined reference to `dlopen'
/tmp/ccRX6ddf.o: In function `test_dlclose':
/home/michal/Documents/projectsc/c-skeleton/tests/libex29_tests.c:49: undefined reference to `dlclose'
collect2: ld returned 1 exit status
make: *** [tests/libex29_tests] Error 1

正如我所说,我尝试将 '-ldl- 添加到 CFLAGS、SO_TARGET 变量,几乎所有内容,根据我的分析,这可能会有所帮助,但这并没有改变任何东西。

4

3 回答 3

7

阅读此问题后:Library Linking

我像这样将 LIBS 更改为 LDLIBS,它对我有用。

LDLIBS=-ldl $(OPTLIBS)
于 2014-03-16T11:30:49.033 回答
0

I think it is not problem of makefile. Probably you have wrong linked files in libex29_tests.c Post your headers from this file and files tree in your direcotry.

于 2013-10-05T14:32:43.943 回答
0

对我有同样问题的工作是添加-Wl,--no-as-needed链接器参数。

于 2014-01-29T15:27:44.320 回答