更新请阅读这个类似但更好的答案: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