Linking to C libraries

I know this is probably really simple and I'm just not grasping it, but how would I link to a compiled library using SPM on Windows?

Specifically I want to mess around with libusb, but I'm not sure how I would construct SPM so that I could wrap it/link to it.

Any help or links to a resource that could walk me through it would be greatly appreciated!

1 Like

Basically, what you would need to do is add a systemLibrary target to your package, that pulls in the necessary #include files through an Umbrella Header, and links against the relevant library. Here is an article that explains this in more detail:

You might want to scroll down to the section that is titled "How to use C system libraries from Swift?" if you are not interested in building your own C library in SPM.

1 Like

Sorry for the late reply to this! Appreciate the response, and you are correct! Following that guide does work on Windows.

The things that confused me were that you needed to have the headers and modulemap somewhere relative to be able to reference and you'll need the .lib and .dll in the root of your consuming swift package.

I think I'm still confused on how to provide another path to the .lib for linking at compilation time. I wonder how you could specify another location instead of dumping it in the root of the project.

I get the DLL gets referenced by the search path when the exe is loaded.

Special shout out to Daniel_Mullenborn for sending me a zipped example that was functioning. I had a blast getting pointers wrong for hours and then finally getting it right!

You can do that, at a cost:

swift build -Xcc -I<include path> -Xlinker -L<linker search path>

This completely shifts the responsibility to the user to specify the library location.

Oh, man. I feel dumb. Thanks for that reply!

By the way, thanks for all your hard work on the Windows port, I haven't accomplished anything useful with Swift for Windows, but I have had a lot of fun and learned a lot!

You're welcome :slight_smile:

Thanks, I'm glad that it has at least given you a way to learn! Hopefully you will find something fun, educational, and useful to do with Swift on Windows :slight_smile: