ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.67k stars 2.47k forks source link

link Library doesn't work on windows with sharedlibrary in build.zig #15903

Open gurpreetshanky opened 1 year ago

gurpreetshanky commented 1 year ago

Zig Version

0.11.0-dev.3312+ab37ab33c

Steps to Reproduce and Observed Behavior

  1. Define a C shared library in build.zig
  2. Link the library with an exe in same build.zig
  3. see unresolved symbols

Using static library works fine.

Expected Behavior

No errors in linking.

gurpreetshanky commented 1 year ago

build_example.zip

check this sample project. If changed from Shared to Static, it is successfully linked. I used this command zig build -Dtarget=x86_64-windows-msvc

kcbanner commented 1 year ago

This may be related: https://github.com/ziglang/zig/issues/15107#issuecomment-1512179905

Are you exporting your functions with __declspec(export) in the shared library?

gurpreetshanky commented 1 year ago

This relates to a work project. The C library is a big project with lot of other functions, it may not be possible to do it for every function. And yes, if I use __declspec(export) in my build example, it works.

kcbanner commented 1 year ago

This is usually accomplished by having some define like FOO_API in front of each function definition, then in the build script you define FOO_API to be __declspec(export) when on Windows.

For example:

        if (engine_shared.target.isWindows()) {
            engine_shared.defineCMacro("STBIDEF", "extern __declspec(dllexport)");
        }

Then, on the consumer side:

        if (exe.target.isWindows()) {
            exe.defineCMacro("STBIDEF", "extern __declspec(dllimport)");
        }
gurpreetshanky commented 1 year ago

thank you very much for providing more info, So If I'm understanding it right, I have to define macro on all functions I need in shared library and then consume that macro in build.zig ?