How do I link using clang-cl?

this is the source code:


#include <SDL.h>

SDL_Window *g_pWindow = 0;

SDL_Renderer *g_pRenderer = 0;

int main(int argc, char *argv[])

{

    if (SDL_Init(SDL_INIT_EVERYTHING))

    {

        g_pWindow = SDL_CreateWindow("Chapter 1: Setting up SDL",

                                     SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,

                                     640, 480,

                                     SDL_WINDOW_SHOWN);

        if (g_pWindow != 0)

        {

            g_pRenderer = SDL_CreateRenderer(g_pWindow, -1, 0);

        }

    }

    else

    {

        return 1;

    }

    SDL_SetRenderDrawColor(g_pRenderer, 0, 0, 0, 255);

    SDL_RenderClear(g_pRenderer);

    SDL_RenderPresent(g_pRenderer);

    SDL_Delay(5000);

    SDL_Quit();

    return 0;

}

these are the paths:

/I C:\SDL2-2.0.22\include

library files for the linker are in the libs folder:

C:\SDL2-2.0.22\lib\x64

SDL2.lib
SDL2main.lib

how do I link against these files?
I’ve worked out this much of it on my own:

clang-cl /EHsc .\Source.cpp /I C:\SDL2-2.0.22\include

In general on windows it’s not common to have the compiler invoke the linker like on Unix based systems. Usually you invoke the linker directly - like lld-link.exe /libpath C:\SDL2-2.0.22\lib\x64 SDL2.lib SD2main.lib myobject.o

But I really recommend you use a build system instead - something like CMake. That will be better for you in the long term.

1 Like

As Tobias said, on Windows it’s more common to invoke the linker separately.

But, letting the compiler invoke the linker is still possible and it can be handy when working with single-file projects like your example. You should be able to just pass the .lib files as arguments to clang-cl, something like:

clang-cl /EHsc Source.cpp /I C:\SDL2-2.0.22\include C:\SDL2-2.0.22\lib\x64\SDL2.lib C:\SDL2-2.0.22\lib\x64\SDL2main.lib

1 Like

Big Thanks Guys.
In the end this command solved the problem. (or I just compile lib files to object files beforehand as said)

clang-cl /EHsc .\Source.cpp /I C:\SDL2-2.0.22\include\ /link /libpath:C:\SDL2-2.0.22\lib\x64 shell32.lib SDL2.lib SDL2main.lib /subsystem:windows /machine:x64

further question:
when I execute:

lld-link /libpath:C:\SDL2-2.0.22\lib\x64 shell32.lib SDL2.lib SDL2main.lib /subsystem:windows /machine:x64

I get a there is no shell32.lib error. but not with the compiler. is there a way to fix this so I can break down compilations steps into several in my final make file?

If you run the clang-cl command with an added -v flag, it will show you how it invokes the linker. Perhaps it’s passing some extra flag.

It might also be worth ruling out if there’s a difference between lld-link and MSVC’s link.exe. Does your command work with link.exe?

I am guessing it’s down to the environment in that case. Maybe LIBS and LIBPATH is set?

Or second thought:

Maybe the clang driver can find the SDK better than the linker can?