Search code examples
c++llvmllvm-clang

Missing CoTaskMemFree when building LLVM example on Windows


I'm attempting to essentially follow the llvm Kaleidoscope example.

I'm on Windows. I built llvm from source per the directions on the site. It took quite a long time but it finally built successfully (no errors at least).

Then with my own code I am running this command:

$  clang-cl main.obj llvm/lib/LLVMCore.lib llvm/lib/LLVMSupport.lib /MDd -o build\test.exe

My main.cpp code has this in it:

#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"

std::unique_ptr<Module> module = llvm::make_unique<Module>("my cool jit", getGlobalContext());

And I'm not getting any parser errors but I am getting an error from the linker that for the life of me I cannot figure out:

LLVMSupport.lib(Path.obj) : error LNK2019: unresolved external symbol
__imp_CoTaskMemFree referenced in function "bool __cdecl 
llvm::sys::path::getKnownFolderPath(struct _GUID,class 
llvm::SmallVectorImpl<char> &)" (?
getKnownFolderPath@path@sys@llvm@@YA_NU_GUID@@AEAV?$SmallVectorImpl@D@3@@Z)

build\test.exe : fatal error LNK1120: 1 unresolved externals

Which library do I have to link to for this function to be defined? I can see the implementation in the code I built from. Do I need to build llvm in a particular way for this to be exported?

EDIT:

It turns out that I needed to read the clang-cl documentation a little better where it says:

To enable clang-cl to find system headers, libraries, and the linker when run from the command-line, it should be executed inside a Visual Studio Native Tools Command Prompt or a regular Command Prompt where the environment has been set up using e.g. vcvars32.bat.

It turns out that this solves my problem. I was a little confused because clang-cl seems to resolve the sdk include and tool paths automatically, but not the lib paths. I also don't want to use CMD to drive clang so I was using bash where I can't run vcvar32.bat easily. I solved my problem by essentially duplicating what vcvar32.bat is doing to the $PATH, $INCLUDE, $LIB and $LIBPATH environment variables and adding Ole32.Lib as a parameter to clang-cl. It then works like a charm.


Solution

  • You're missing the CoTaskMemFree symbol. A quick look on the Internet suggests you'll need the Ole32 system library on your link line.

    I don't have access to a Windows machine to test on, but on my computer, I can run llvm-config --system-libs and it pulls in the all the necessary things. After adding using namespace llvm; and adding a stub main function, I can easily build this example with (on OSX):

    c++ `llvm-config --cxxflags` main.cpp `llvm-config --ldflags --system-libs --libs core support`
    

    I often recommend just specifying --libs rather than guessing what you'll need, but your choice.