Search code examples
c++visual-studiogradlevcpkg

Gradle - Visual C++ compiler, vcpkg and external libraries


I have Visual Studio 2019 installed, alongside the vcpkg. I have installed an external dependency (msmpi using vcpkg install msmpi:x86-windows) and tried creating sample MPI project using Visual Studio IDE: everything works, no additional configuration was needed, impressive.

Now - due to the nature of the project I am working on, I wanted to use gradle to compile my code (outside of Visual Studio). In pursuit of that I have used Gradle's cpp-application plugin, with the following build.gradle:

plugins {
    id 'cpp-application'
}

The compilation of simple "Hello world" works: gradle finds Visual C++ compiler, executes it and everything works without a hitch (I was impressed as well, by the way).

The problem arose when I included the header from external library (mpi.h) into my code. It seems that the dependencies installed beforehand with vcpkg are not visible when gradle and cpp-application plugin are used for compilation (everything worked without any additional configuration when I compiled the code using Visual Studio IDE). How can the problem be remedied, preferably without hard-coding library and headers into my build.gradle?


Solution

  • I was able to get gradle to compile my project, by supplying it with paths to vcpgk-installed mpi headers and libraries. I will be looking for a way of making it more flexible. Nevertheless, here are my additions to build.gradle:

    ext {
        vcpgkIncludePath = 'path-to-include'
        vcpkgLibPath = 'path-to-vcpkg-libs'
    }
    tasks.withType(CppCompile).configureEach {
        compilerArgs.addAll toolChain.map { toolChain ->
            if (toolChain in VisualCpp) {
                return ["/I$vcpgkIncludePath"]
            }
            return []
        }
    }
    
    tasks.withType(org.gradle.nativeplatform.tasks.LinkExecutable).configureEach {
        linkerArgs.addAll toolChain.map { toolChain ->
            if (toolChain in VisualCpp) {
                return ["/LIBPATH:$vcpkgLibPath", "msmpi.lib"]
            }
            return []
        }
    }