在工程中用到使用Python調用C++編寫的動態庫,結果報以下錯誤:ios
OSError: ./extract_str.so: undefined symbol: _ZNSt8ios_base4InitD1Evc++
Python調用函數函數
1 #coding:utf-8 2 from ctypes import * 3 4 libpcre = cdll.LoadLibrary("./extract_str.so") 5 pcre="^GirlFriend\s+Server\s+\d+\x2E\d+\s+\x2E\s+port\s+\d" 6 ret = libpcre.extract_exact_strings(pcre, len(pcre), 4, max_str, max_str_len, expr_str, expr_str_len) 7 if ret == 1: #解析成功 8 print(ret) 9 print(max_str) 10 print(expr_str) 11 else: #解析失敗 12 print("ret is not 1!")
加載目錄文件
spa
報錯:prototype
執行nm命令
code
經過搜索知道ios_base4Init 是C++標準輸入輸出函數庫,說明該庫未被加載。搜索知道是因爲連接的問題。blog
Stackoverflow連接:http://stackoverflow.com/questions/10906275/undefined-reference-to-stdios-baseinitinitutf-8
查看Makefilestring
1 CC = gcc 2 CCC = g++ 3 CFLAGS = -g -Wall $(OPEN_O2) -Wstrict-prototypes -fPIC 4 CPPFLAGS = -g -Wall $(OPEN_O2) -fPIC 5 INCS = -I../include 6 SOURCES = $(wildcard *.c *.cpp) 7 OBJS = $(patsubst %.cpp,%.o, $(patsubst %.c, %.o, $(SOURCES))) 8 TARGETS = extract_str.a 9 SHARD_TARGETS = extract_str.so 10 11 .PHONY: all clean 12 13 .c.o: 14 $(CC) -c $(CFLAGS) -I. $(INCS) $< 15 .cpp.o: 16 $(CCC) -c $(CPPFLAGS) -I. $(INCS) $< 17 18 all: $(TARGETS) $(SHARD_TARGETS) 19 20 clean: 21 rm -f *.a *.o core core.* *~ 22 rm ../lib/$(TARGETS) 23 rm ../lib/$(SHARD_TARGETS) 24 25 $(TARGETS): $(OBJS) 26 ar -cr ../lib/$@ $^ 27 28 $(SHARD_TARGETS): $(OBJS) 29 $(CC) -shared -o ../lib/extract_str.so $^
源文件爲C++,在生成動態庫時使用的是gcc,致使C++標準庫未被連接。兩種修改方式it
1. 用g++編譯,命令改成:
1 $(CCC) -shared -o ../lib/extract_str.so $^
2. 繼續使用gcc編譯,添加連接參數 –lstdc++ 命令改成:
1 $(CC) -shared -o ../lib/extract_str.so $^ -lstdc++