Unable to Link C system libs on windows

I have just started learning swift and I am trying to use GLFW but am unable to link it

I am running

swift build -Xswiftc -IC:\glfw-338\include -Xlinker -LC:\glfw-338\lib-vc2022 

and I get a bunch of undefined symbol errors. Some of these symbols seem to be private and are not in the header.

lld-link: error: undefined symbol: __declspec(dllimport) ShowWindow
>>> referenced by glfw3.lib(win32_init.obj):($LN42)
>>> referenced by glfw3.lib(win32_window.obj):($LN39)
>>> referenced by glfw3.lib(win32_window.obj):($LN39)
>>> referenced 6 more times

lld-link: error: undefined symbol: __declspec(dllimport) ToUnicode
>>> referenced by glfw3.lib(win32_init.obj):($LN16)
>>> referenced by glfw3.lib(win32_init.obj):($LN16)
>>> referenced by glfw3.lib(win32_init.obj):($LN42)
>>> referenced 1 more times

I think it is linking to the lib instead of the dll or something like that. How do I fix this?

package.swift

import PackageDescription

let package = Package(
    name: "example",
    targets: [
        .executableTarget(
            name: "example",
            dependencies: ["CGLFW"],
            path: "Sources"
            ),
        .systemLibrary(
            name: "CGLFW",
            path: "External/CGFLW"
        )
    ]
)

module.modulemap

module CGLFW [system] {
    header "shim.h"
    link "glfw3"
    export *
}

What I do on Windows is copy the headers and lib/dlls into my project, for example, in examplecglfwinclude and examplecglfwlib

Then, in your shim.h, you can do something like:

#ifdef _WIN64
    #include "glfw3.h" (or whatever the header is called)
#endif

and in Package.swift:

let package = Package(
    name: "example",
    targets: [
        .executableTarget(
            name: "example",
            dependencies: ["CGLFW"],
            path: "Sources",
            swiftSettings: [.unsafeFlags(["-Icglfw/include"])],
            linkerSettings: [.unsafeFlags(["-Lcglfw/lib"])]
        ),
        .systemLibrary(
            name: "CGLFW",
            path: "External/CGFLW"
        )
    ]
)

Not that this is just an example based on one of my own projects (I didn't run this), so it may have typos.

You will also need to copy the DLLs to the same output directory as your executable (unless you installed them globally), otherwise they will not be found.

2 Likes

Thanks!

I installed the dll globally and it got rid of the linker error.