Eclipse で C++ (その5)

DLLの作成

次に前回作成した関数を DLL にする。

DLL にするには、ソースに以下の変更を加える。
DllEntryPoint を追加。 おまじない DLLEXPORTfunc1 を外部から参照できるようにする。

リンク時に -mdll で DLL の作成を指定する。 続いて dlltool で DEF ファイルとライブラリーを作成する。

最終的に myFunc.Dll,myFunc.Def,libmyFunc.a の三つのファイルが出来る。

func1.cpp

#include 
#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT int _stdcall func1(int a,int b)
{
  return (a+b);
  }

//*****************************************************************************
DLLEXPORT bool   DllEntryPoint(HINSTANCE hInstance, DWORD fdwReason, LPVOID  lp){
  switch (fdwReason){
    case DLL_PROCESS_ATTACH: //ロードされるときの処理
// false を返すと DLL はロードされない。
      return true;

    case DLL_PROCESS_DETACH: //アンロードされるときの処理
      return true;

    case DLL_THREAD_ATTACH:
      return true;

    case DLL_THREAD_DETACH:
      return true;
    }
  return true;
  }

Makefile

DEBUG=1

DLL = myFunc
OBJS =	func1.o 

# リンカーオプション
LDFLAGS = 

TARGET =	$(DLL).Dll

CXXFLAGS = -c -Wall -fmessage-length=0 

ifeq ($(DEBUG),1)
CXXFLAGS += -O0 -g  -D_DEBUG
else
CXXFLAGS += -Os   
endif


$(TARGET):	$(OBJS)
	g++ -mdll -o $(TARGET) $(OBJS) $(LINKS) -e DllEntryPoint
	dlltool   --export-all --output-def $(DLL).def $(OBJS) 
	dlltool  --dllname $(DLL) --def $(DLL).def --output-lib lib$(DLL).a  

all:	$(TARGET)

clean:
	del *.bak
	del *.o
	del *.dll
	del *.a
	del *.def

DLL の呼出

以下のようなソースを用意した。
おまじない DLLIMPORT で DLL 関数を呼べるようにする。
また、リンカーオプションで上で作成したライブラリーを指定する。

test.cpp

#include 
using namespace std;

#define DLLIMPORT extern "C" __declspec(dllimport)
DLLIMPORT int func1(int a,int b);

int main(void) {

	cout << "func1(10,5)= " << func1(10,5) << endl;

	return EXIT_SUCCESS;
}

Makefile

DEBUG=1

DLL = myFunc
OBJS =	test.o 


# リンカーオプション
LDFLAGS = 
LIBS =  -L. -lMyFunc

TARGET =	test.exe

CXXFLAGS = -c -Wall -fmessage-length=0 

ifeq ($(DEBUG),1)
CXXFLAGS += -O0 -g  -D_DEBUG
else
CXXFLAGS += -Os   
endif


$(TARGET):	$(OBJS)
	$(CXX) -o $(TARGET) $(OBJS) $(LIBS)


all:	$(TARGET)

clean:
	del *.bak
	del *.o
	del *.exe


その4   戻る