移除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
相关产品推荐
相关产品推荐

