How to link against winsock library in C++


(Antonio Ontiveros) #1

I seem to be encountering issues when attempting to build a small application that links against the WinSock library. I have tried multiple things such as adding my Windows SDK to the linker args as well as explicitly adding the winsock library to the libraries of the executable component.

Here is what my build.gradle looks like:

model {
    components {
        main(NativeExecutableSpec){
            sources {
                  cpp {
                    source {
                        srcDir 'src/'
                        include '**/*.cpp'
                        include '**/*.h'
                    }
                }
            }
        }
    }
    binaries {
        all {
            if (toolChain in VisualCpp) {
                linker.args "/SUBSYSTEM:CONSOLE"
            }
        }
        withType(NativeExecutableSpec) {
            lib library: "WS2_32", linkage: "static"
        }
    }
}

(Alexander Volanis) #2

The code you added in the withType closure only works if you also define the WS2_32 library as a prebuilt library. You would need to look at the example provided by the gradle team in /samples/native-binaries/prebuilt.

model {
    repositories {
        libs(PrebuiltLibraries) {
            WS2_32 {
                headers.srcDir 'full/path/to/win32/headers/directory'
                binaries.withType(StaticLibraryBinary) {
                    staticLibraryFile = file('full/path/to/win32/winsock.lib')
                }
            }
        }
    }
}