Why I am getting build error when I have 2 functions of same name in different lib in a workspace?

Hi All,

I have been learning Rust for couple of months now and I started using Workspace. I have broken my modules to lib so that compile time reduces and I can use python with FFI. Strangely, I am getting an build error. is it possible to avoid this error?

├── Cargo.lock
├── Cargo.toml
├── lib_1
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── lib_2
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── my_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

Then, I have below function in lib_1

// lib_1/src/lib.rs
#[no_mangle]
pub extern "C" fn get_as_json(path: *const c_char) -> *mut c_char {
    // Do my code for lib_1
}

Likewise, in lib_2,

// lib_2/src/lib.rs
#[no_mangle]
pub extern "C" fn get_as_json(path: *const c_char) -> *mut c_char {
    // Do my code for lib_2
}

When I do cargo build, I am getting below error

liblib_1.rlib(lib_1.210c57avucod57l9.rcgu.o) : error LNK2005: get_as_json already defined in liblib_2.rlib(lib_2.55by53wmm0ypf63d.rcgu.o)

If you use #[no_mangle] the normal name mangling that is used to prevent symbol conflicts is turned off. This is useful when interacting with C code, as C doesn't do name mangling. It does mean that symbol conflicts will give a linker error, just like in C code.

2 Likes

C doesn't have any concept of isolated modules or separate crates. In C every function name is in the same global namespace. #[no_mangle] puts functions in that global C namespace where they collide with each other.

ah okay. Sorry I have limited knowledge on C. Thanks @bjorn3 and @kornel, Since, I don't have choice I will have to use 2 different function names.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.