我正在尝试用windows上的一个简单的C库连接到Rust库
我的库是.h
extern "C" {
void say_hello(const char* s);
}
.cpp
#include <stdio.h>
void say_hello(const char* s) {
printf("hello world");
}
我的锈菌档案
#[link(name="CDbax", kind="static")]
extern "C" {
fn say_hello(s: *const libc::c_char) -> () ;
}
链接失败,因为使用其中一个数据符号时出现错误。
error: linking with `gcc` failed: exit code: 1
note: "gcc" "-Wl,--enable-long-section-names" "-fno-use-linker-plugin" "-Wl,--nxcompat" "-Wl,--large-address-aware" "-shared-libgcc" "-L" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.o" "-o" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.dll" "e:\Rust\DBTools\DBAnalytics\target\debug\DBAnalytics.metadata.o" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\libstd-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\libcollections-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\librustc_unicode-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\librand-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\liballoc-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\liblibc-11582ce5.rlib" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib\libcore-11582ce5.rlib" "-L" "e:\Rust\DBTools\DBAnalytics\target\debug" "-L" "e:\Rust\DBTools\DBAnalytics\target\debug\deps" "-L" "C:\Program Files (x86)\Rust 1.2\bin\rustlib\i686-pc-windows-gnu\lib" "-L" "e:\Rust\DBTools\DBAnalytics\.rust\bin\i686-pc-windows-gnu" "-L" "e:\Rust\DBTools\DBAnalytics\bin\i686-pc-windows-gnu" "-Wl,-Bstatic" "-Wl,--whole-archive" "-l" "CDbax" "-Wl,--no-whole-archive" "-Wl,-Bdynamic" "-l" "ws2_32" "-l" "userenv" "-l" "advapi32" "-shared" "-l" "compiler-rt"
note: Warning: corrupt .drectve at end of def file
Cannot export ??_C@_0M@LACCCNMM@hello?5world?$AA@: symbol not found
这个库是作为一个简单的静态库构建在MSVC2013上的。字符串"hello world“位于data部分,因此我不认为它会导致链接错误。在与windows上的C库链接时,是否需要注意一些特定的设置?
顺便说一下,它是32位的MSVC库。
发布于 2015-06-09 07:52:11
好吧,有几件事。首先,没有所谓的“静态DLL":DLL是一个动态链接库。
其次,Rust使用MinGW工具链和运行时。混合MSVC和MinGW运行时可能会导致奇怪的事情发生,所以如果可能的话,最好避免。铁锈直到最近才开始支持使用MSVC运行时进行构建。
然而,您可以让这个具体的例子工作,显然没有任何不良影响。你只需要改变几件事:
say_hello
链接来实际编译C
,而不是C++
链接。您在头文件中这样做,但在源文件中没有这样做。say_hello
。因此:
hello.rs
#[link(name="hello", kind="dylib")]
extern {
fn say_hello();
}
fn main() {
unsafe { say_hello(); }
}
hello.h
#ifndef HELLO_H
#define HELLO_H
extern "C" {
__declspec(dllexport) void say_hello();
}
#endif
hello.cpp
#include <cstdio>
#include "hello.h"
void say_hello() {
printf("hello world\n");
}
build.cmd
cl /LD hello.cpp
rustc -L. hello.rs
在我的机器上,这会产生hello.exe
和hello.dll
;运行时,hello.exe
会打印出hello world
。
https://stackoverflow.com/questions/30725579
复制相似问题