1.在Makefile中创建动态库。

2.在动态库中共享class类型。

 

Makefile文件如下:

EXE=libexample.so
SUBDIR=src

CXX_SOURCES=$(foreach dir,$(SUBDIR),$(wildcard $(dir)/*.cpp))
CXX_OBJECTS=$(patsubst %.cpp, %.o, $(CXX_SOURCES))
DEP_FILES=$(patsubst %.o,%d, $(CXX_OBJECTS))

$(EXE): $(CXX_OBJECTS)
	g++ -shared $(CXX_OBJECTS) -o $(EXE)
	
%.o: %.cpp
	g++  -c -fPIC -MMD $<  -o  $@

-include $(DEP_FILES)

clean:
	rm -rf $(CXX_OBJECTS) $(DEP_FILES) $(EXE)
	
test:
	echo $(CXX_OBJECTS)

文件目录结构如下:

src文件内部如下:

源码:

example.h


class Object{
	public:
	void test();
	int id;
};

int example(int a,int b);

example.cpp


#include <stdio.h>
#include "example.h"

int example(int a, int b)
{
	printf("example library: a=%d, b=%d \n", a, b);
	return 0;
}

void Object::Test()
{
	printf("id=%d \n", id);
}


main.cpp

#include "src/example.h"

int main(){
	example(10,20);
	
	Object obj;
	obj.id=100;
	obj.test();
	
	return 0;
}

 

运行截图如下:

Logo

更多推荐