You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除Address Sanitizer后Linux共享库出现未定义引用错误

Linux下共享库链接异常问题:移除地址Sanitizer后出现未定义引用

我是C语言新手,在Ubuntu 20.04 LTS环境下构建测试用共享库时遇到异常:当Makefile中添加-fsanitize=address编译标志时,共享库可正常编译并链接;但移除该标志后,编译main程序时会报foo未定义引用的错误。

错误信息

/usr/bin/ld: /tmp/ccjVftXd.o: in function `main':
main.c:(.text+0x9): undefined reference to `foo'
collect2: error: ld returned 1 exit status
make: *** [makefile:31: main] Error 1

测试代码示例

foo.c

int foo(void) {
    return 1;
}

main.c

extern int foo(void);

int main(void) {
    return foo();
}

Makefile内容

# my makefile
# Compiler options
CC = gcc
CFLAGS = -Wall -fPIC

# Sanitizer
# this is commented and would get the error.
# CFLAGS += -fsanitize=address

# Target library
# add your lib path here
LIB_ROOT = ...
LIBRARY = $(LIB_ROOT)/libfoo.so

# Source files
SRCS = foo.c

# Object files
OBJS = $(SRCS:.c=.o)

# Default target
all: $(LIBRARY) main

# Compile source files into object files
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# Link object files into shared library
$(LIBRARY): $(OBJS)
	$(CC) $(CFLAGS) -shared $^ -o $@

# Compile main.c using the library
main: main.c $(LIBRARY)
	$(CC) $(CFLAGS) -L$(LIB_ROOT) -lfoo main.c -o main

# Clean build artifacts
clean:
	rm -f $(OBJS) $(LIBRARY) main

构建日志

>>> make
gcc -Wall -fPIC -c foo.c -o foo.o
gcc -Wall -fPIC -shared foo.o -o /my/path/libfoo.so
gcc -Wall -fPIC -L/my/path/lib -lfoo main.c -o main
/usr/bin/ld: /tmp/ccTbYeMl.o: in function `main':
main.c:(.text+0x9): undefined reference to `foo'
collect2: error: ld returned 1 exit status
make: *** [makefile:31: main] Error 1

共享库信息(执行nm -D /my/lib/path/libfoo.so结果)

w __cxa_finalize
00000000000010f9 T foo
                 w __gmon_start__
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable

内容的提问来源于stack exchange,提问作者xkkdd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:35:23