Skip to content

link: failed to static link to c++ library when global variable is used #36710

Closed

Description

Hi, I am trying to build a binary written in rust static linked with a c++ library. I follow the instructions in official documentation, but end up with an error:

undefined reference to `__dso_handle'

Following is a simple example:

// test.cpp
#include <vector>

const std::vector<int> ids = {2, 3, 4};

extern "C" {
    extern int get_id(int idx);
}

int get_id(int idx) {
    return ids[idx];
}
// main.rs
#[link(name = "test")]
extern "C" {
    pub fn get_id(idx: usize) -> usize;
}

fn main() {
    unsafe {
        println!("id at {} is {}", 2, get_id(2));
    }
}

I build the static library using following command:

g++ -std=c++0x -c test.cpp -o test.o
ar rcs libtest.a test.o

And build the binary using following command:

LIBRARY_PATH=./ rustc main.rs -lstdc++ --target=x86_64-unknown-linux-musl

It failed with error:

note: ./libtest.a(test.o): In function __static_initialization_and_destruction_0(int, int)': test.cpp:(.text+0xa2): undefined reference to__dso_handle'
/usr/local/lib/rustlib/x86_64-unknown-linux-musl/lib/libstd-8102e29f.rlib(std-8102e29f.0.o):(.data._rust_extern_with_linkage___dso_handle+0x0): undefined reference to `__dso_handle'

I can build the binary successfully when linking dynamically. Am I missing any thing here? Any help is appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)A-linkageArea: linking into static, shared libraries and binariesC-bugCategory: This is a bug.O-muslTarget: The musl libcT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions