動態連結庫的生成和使用(二)

轩邈、發表於2024-08-31

1、編寫原始檔和標頭檔案

Demo目錄下建立testso資料夾在下面建立test.cpp、test.h和Makefile檔案

test.cpp:

#include <stdio.h>
#include <stdlib.h>
extern "C"
double calc_pi()
{
	double x = 0;
	double y = 0;
	double pi = 0;
	int num = 0;
	int iter = 0;
	const int try_times = 10000000;
	const double max_val = 32767.0;
	while (iter++ <= try_times)
	{
		x = (double)(rand() % 32768) / max_val;
		y = (double)(rand() % 32768) / max_val;
		if ((x * x + y * y) <= 1)
			num++;
	}
	pi = (4.0 * num) / try_times;
	return pi;
}

test.h

extern "C"
double calc_pi();

Makefile檔案

EXECUTABLE:= libtest.so
LIBDIR:=
LIBS:=
INCLUDES:=.
SRCDIR:=

CC:=g++
CFLAGS:= -g -fPIC -Wall -O0 
CPPFLAGS:= $(CFLAGS)
CPPFLAGS+= $(addprefix -I,$(INCLUDES))
CPPFLAGS+= -I.
CPPFLAGS+= -MMD

RM-F:= rm -f

SRCS:= $(wildcard *.cpp) $(wildcard $(addsuffix /*.cpp, $(SRCDIR)))
OBJS:= $(patsubst %.cpp,%.o,$(SRCS))
DEPS:= $(patsubst %.o,%.d,$(OBJS))
MISSING_DEPS:= $(filter-out $(wildcard $(DEPS)),$(DEPS))


.PHONY : all deps objs clean
all:$(EXECUTABLE)
deps:$(DEPS)

objs:$(OBJS)
clean:
	@$(RM-F) *.o
	@$(RM-F) *.d

ifneq ($(MISSING_DEPS),)
$(MISSING_DEPS):
	@$(RM-F) $(patsubst %.d,%.o,$@)
endif
-include $(DEPS)
$(EXECUTABLE) : $(OBJS)
	$(CC) -shared -o $(EXECUTABLE) $(OBJS) $(addprefix -L,$(LIBDIR)) $(addprefix -l,$(LIBS))

相關文章