更新請閱讀這個類似但更好的答案:https://stackoverflow.com/a/14777895/938111
make (和 gcc )可以使用Cygwin或MinGW在MS-Windows上輕松安裝 .
正如@ldigas所說, make 可以使用 UNAME:=$(shell uname) 檢測平臺(命令 uname 也由Cygwin或MinGW安裝程序安裝) .
下面,我提供了一個基于 make (和 gcc )的完整示例來解釋如何構建共享庫: *.so 或 *.dll ,具體取決于平臺 .
這個例子基本/簡單易于理解:-)
我們來看看五個文件:
├── app
│ └── Makefile
│ └── main.c
└── lib
└── Makefile
└── hello.h
└── hello.c
Makefiles
app/Makefile
app.exe: main.o
gcc -o $@ $^ -L../lib -lhello
# '-o $@' => output file => $@ = the target file (app.exe)
# ' $^' => no options => Link all depended files
# => $^ = main.o and other if any
# '-L../lib' => look for libraries in directory ../lib
# '-lhello => use shared library hello (libhello.so or hello.dll)
%.o: %.c
gcc -o $@ -c $< -I ../lib
# '-o $@' => output file => $@ = the target file (main.o)
# '-c $ COMPILE the first depended file (main.c)
# '-I ../lib' => look for headers (*.h) in directory ../lib
clean:
rm -f *.o *.so *.dll *.exe
lib/Makefile
UNAME := $(shell uname)
ifeq ($(UNAME), Linux)
TARGET = libhello.so
else
TARGET = hello.dll
endif
$(TARGET): hello.o
gcc -o $@ $^ -shared
# '-o $@' => output file => $@ = libhello.so or hello.dll
# ' $^' => no options => Link all depended files => $^ = hello.o
# '-shared' => generate shared library
%.o: %.c
gcc -o $@ -c $< -fPIC
# '-o $@' => output file => $@ = the target file (hello.o)
# '-c $ compile the first depended file (hello.c)
# '-fPIC' => Position-Independent Code (required for shared lib)
clean:
rm -f *.o *.so *.dll *.exe
源代碼
app/main.c
#include "hello.h" //hello()
#include //puts()
int main()
{
const char* str = hello();
puts(str);
}
lib/hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
const char* hello();
#endif
lib/hello.c
#include "hello.h"
const char* hello()
{
return "hello";
}
構建
修復 Makefiles copy(通過制表替換前導空格) .
> sed -i 's/^ */\t/' */Makefile
兩個平臺上的 make 命令相同 . 這是MS-Windows上的輸出(刪除了不必要的行) .
> cd lib
> make clean
> make
gcc -o hello.o -c hello.c -fPIC
gcc -o hello.dll hello.o -shared
> cd ../app
> make clean
> make
gcc -o main.o -c main.c -I ../lib
gcc -o app.exe main.o -L../lib -lhello
跑步
應用程序需要知道共享庫的位置 .
在MS-Windows上,簡單/基本/愚蠢的方法是復制應用程序所在的庫:
> cp -v lib/hello.dll app
`lib/hello.dll' -> `app/hello.dll'
在Linux上,使用 LD_LIBRARY_PATH 環境變量:
> export LD_LIBRARY_PATH=lib
兩個平臺上的運行命令行和輸出相同:
> app/app.exe
hello