Using Libraries in C++ (Static Linking)

Estimated read time: 1:20

    Learn to use AI like a Pro

    Get the latest AI workflows to boost your productivity and business performance, delivered weekly by expert consultants. Enjoy step-by-step guides, weekly Q&A sessions, and full access to our AI workflow archive.

    Canva Logo
    Claude AI Logo
    Google Gemini Logo
    HeyGen Logo
    Hugging Face Logo
    Microsoft Logo
    OpenAI Logo
    Zapier Logo
    Canva Logo
    Claude AI Logo
    Google Gemini Logo
    HeyGen Logo
    Hugging Face Logo
    Microsoft Logo
    OpenAI Logo
    Zapier Logo

    Summary

    In this video, The Cherno delves into the subject of using libraries in C++. Specifically, he tackles the concept of static linking of external libraries, contrasting it with the use of dynamic libraries. He explains the process of including necessary files, linking libraries in Visual Studio, and the pros and cons of static versus dynamic linking. By walking through a detailed example with the GL FW library, viewers are guided step-by-step on how to link these libraries both statically and dynamically, understanding the intricate processes involved.

      Highlights

      • The Cherno emphasizes keeping everything needed within the code repository for easier project setup. 📁
      • Static linking includes libraries in the executable, improving startup speed and simplicity. 🚀
      • Dynamic linking requires the library to be available at runtime, allowing for updates without recompiling the app. 🔄
      • He advises using Visual Studio's macro feature to manage paths, making the setup more flexible. ⚙️
      • Choosing the right architecture (32-bit or 64-bit) for your application is crucial for successful linking. 🧐

      Key Takeaways

      • Library linking in C++ can seem daunting but is manageable once you break it down! 💡
      • Static linking involves adding libraries directly into your executable, ensuring everything stays together. 📦
      • Dynamic linking connects libraries at runtime, allowing for flexibility and modularity. 🔗
      • Always ensure compatibility between the binaries and your application's target architecture! 🏗️
      • Using relative paths improves project portability across different machines. 🚚

      Overview

      In this episode by The Cherno, the focus is on demystifying the use of libraries in C++ projects. The video caters to both beginners and seasoned programmers who might find incorporating libraries into C++ projects a tricky business. By dissecting static and dynamic linking, The Cherno simplifies the process, ensuring that viewers understand the step-by-step actions required to effectively link libraries.

        The video critiques the use of package managers for C++ and emphasizes the benefits of having a self-contained repository where all libraries are included. This practice not only simplifies compiling for different users but also enhances the understanding of how the linking process works within Visual Studio.

          Following along with the integration of the GL FW library, viewers learn to set up both static and dynamic links. The Cherno explains the nuts and bolts of using Visual Studio effectively for library management, including using macros for path definitions and ensuring architecture compatibility. This deep dive, surprisingly stretched beyond initial time expectations, is all about making sure developers can handle library linking with ease and confidence.

            Chapters

            • 00:00 - 00:30: Introduction and Overview In this introduction chapter, the host Chana welcomes viewers to the C++ series and sets the stage for discussing the use of external libraries in C++. Unlike other languages like Java, C#, or Python where adding libraries is straightforward, C++ often presents challenges in this area. The host acknowledges past struggles with this topic, suggesting it will be a focus of the chapter.
            • 00:30 - 01:00: Project Setup and Dependencies This chapter deals with setting up a project and managing dependencies in C++. It introduces different strategies for handling libraries, with the author's personal preference for C++ library integration, highlighting a reluctance towards using package managers or linking to external repositories. Instead, it emphasizes the author's ideal setup where the code repository should be self-contained, allowing for straightforward usage upon checkout.
            • 01:00 - 01:30: Handling Dependencies in C++ The chapter discusses the importance of having all necessary dependencies readily available within a C++ project repository to simplify compilation and execution without requiring external library downloads. The author expresses a desire for a seamless experience, emphasizing frustration with package managers and external dependencies specific to C++.
            • 01:30 - 02:00: Compiling vs Linking Against Libraries The chapter discusses the decision-making process between compiling libraries or linking against precompiled ones in software development. It highlights the importance of maintaining versions of dependencies within the project folder to ensure the project compiles and runs successfully. The choice between compiling libraries oneself or linking against existing ones is also explored.
            • 02:00 - 02:30: Linking Against Binaries For significant projects, it's best to build from the source code, especially if using tools like Visual Studio. This involves adding a new project for the source code of the dependency and compiling it into a static or dynamic library. However, for quick or insignificant projects where source code isn't accessible or the setup isn't worth the time, using pre-built binaries may be more practical. This approach is quicker and easier when the project isn't serious.
            • 02:30 - 03:00: Demonstration with GLFW In this chapter, the focus is on working with GLFW, a library used in OpenGL and graphics programming. The approach taken involves linking against binaries rather than compiling the library from source code. The video referenced is part of an OpenGL series, specifically mentioning episode 2 as a resource where GLFW was downloaded and linked. The speaker also notes that compiling from source could be a topic for a future video if there's interest from the audience.
            • 03:00 - 03:30: Building Libraries on Different OS This chapter discusses the challenges of building libraries on different operating systems. It touches on the availability of binaries for various OS platforms and the tendency for UNIX systems users, like those on Mac and Linux, to build their own code. This is contrasted with Windows users, who generally prefer ready-to-use binaries for convenience. Suggestions for addressing these challenges within a real application context are also offered.
            • 03:30 - 04:00: Static vs Dynamic Libraries In this chapter titled 'Static vs Dynamic Libraries,' the focus is on the benefits of compiling libraries versus using precompiled binaries. The speaker argues that compiling the library yourself is advantageous for debugging and modifying the library, as it integrates the source code into your development environment. Despite these benefits, many resources, like the gfw library available at Chillicothe.org, provide precompiled binaries which might be more convenient but offer less flexibility for developers who want to tweak or debug the library's functionality.
            • 04:00 - 04:30: Setting Up GLFW in Visual Studio The chapter discusses downloading precompiled binaries for Windows to set up GLFW in Visual Studio. For Linux and macOS, compiling from source is necessary. The choice between 32-bit and 64-bit binaries depends on the target application, not the operating system.
            • 04:30 - 05:00: Include Directories and Compiler Setup The chapter titled 'Include Directories and Compiler Setup' discusses the process of compiling applications as either 32-bit or 64-bit on a Windows platform. It emphasizes the importance of matching application architecture (32-bit or 64-bit) with the correct set of binaries to ensure successful linking. In this particular example, a 32-bit application is being compiled and thus requires the 32-bit Windows binaries. Once these binaries are downloaded and extracted, they are organized in a standard folder structure typically used for this purpose.
            • 05:00 - 05:30: Linking Libraries in Visual Studio This chapter discusses how to link libraries in Visual Studio, specifically focusing on C++ libraries which typically involve two main components: includes and libraries. It explains that an include directory consists of header files necessary for using the functions provided by the library. The chapter refers to an external video for in-depth explanation of linking, illustrating where to find additional information on how linking works in programming.
            • 05:30 - 06:00: Compiling and Linking Demonstration In this chapter titled 'Compiling and Linking Demonstration', the discussion focuses on the concept of pre-built binaries and their organization within the lint directory. The content delves into the two main types of libraries: dynamic and static libraries, emphasizing that not all libraries support both forms. The example of 'jello W' is given, highlighting its capability to link either statically or dynamically based on the user's choice. Although a detailed comparison between static and dynamic linking is deferred to another video, a brief explanation is provided. It is mentioned that static linking involves incorporating certain elements directly into the application.
            • 06:00 - 06:30: Conclusion and Upcoming Topics The chapter concludes by discussing how static libraries become part of the executable, while dynamic libraries are linked at runtime. It highlights the use of the load library function in the Windows API for loading dynamic libraries and obtaining function pointers. This sets the stage for upcoming discussions on library usage and management in different operating systems.

            Using Libraries in C++ (Static Linking) Transcription

            • 00:00 - 00:30 hey what's up guys my name is a chana welcome back to my say plus plus series festival haircut second of all today I'm gonna be talking all about libraries in C++ and specifically how we can use external libraries in our project so if you used to other languages such as Java or C sharp or Python or something like that adding libraries is a pretty trivial task you might be using a package manager you might not be but either way it's usually pretty straightforward when it comes to C++ everyone seems to have problems and back in the day I had issues with this as well and I don't
            • 00:30 - 01:00 even know why it's there actually really simple and hopefully this video will kind of help clear it up for you but basically there are a few strategies that we can actually take when we're dealing with libraries in C++ and I'm gonna kind of show you my way as well as maybe discuss some of the other ones but first of all I hate the idea of package managers and I hate the idea of linking to kind of other repositories or all that stuff my my ideal project setup is that if you check out my repository my code repository from github or whatever
            • 01:00 - 01:30 you should have everything you need in that repository just straight away fee for you to actually be able to compile and run the application or the project or whatever right there should be no kind of syncing up with package managers downloading other libraries all that stuff I hate all of that I just want especially with C++ there are some package managers for other kind of languages which makes sense I'm specifically obviously talking about C++ this is the C++ series but for C++ I just want stuff to work I just want to
            • 01:30 - 02:00 be able to clone the repository and I want it to compile and run so for that reason I tend to actually keep versions of my dependencies all the libraries that I'm using in the actual solution in the actual project folder so I've actually got copies of those that visit those physical binaries or code depending on which way I go without as well in my actual kind of working directory of my solution that kinda brings me to another point should I be compiling these myself or should I just be linking against
            • 02:00 - 02:30 pre-built binaries now for most serious projects I would absolutely recommend actually building the source code if you're using Visual Studio you can just add another project which contains your kind of source code of your dependency of your library and then compiled that into either a static or dynamic library however if you don't have access to the source code or if you're planning just this is a quick project I don't want to spend time setting this up because it's kind of a throwaway thing or it's just a it's nothing serious then I would probably lean against the binaries because it's just gonna be quicker and easier so
            • 02:30 - 03:00 today specifically we're going to be linking against binaries we're not going to be grabbing the source code of an actual kind of dependency of an actual library and compiling it ourselves I might save that for another video if you're interested in that let me know leave a comment below but today we're just gonna be dealing with binaries and specifically what we're going to be dealing with is a library called GL FW now my open GL series which is all about OpenGL and graphics program you saw like that in episode 2 which I've linked up there as well we actually did download gel of W and Lincoln so you can take a look at that if you'd like maybe I show some extras some extra things there but
            • 03:00 - 03:30 today we're actually going to go through it slowly and take a look at everything but if you kind of want to see it in a context of a real application then check that series out another thing to note is the binaries might not be available for your actual project right for your actual library that you want to link so you may actually be forced to build it yourself this is especially true with like Mac and Linux because for UNIX systems people usually just love building code for Windows a lot of people who use windows just want stuff to work like like me I just want things to work so that's why preview binaries
            • 03:30 - 04:00 exist and again I'm just saying that in a more kind of professional a lot of project in in a space where I actually had time I would for sure compile it myself because it helps with debugging it helps with if you want to modify the library and change it a little bit I do that quite frequently I just love having it having the source code right there in the visual studio solution but today let's talk about binaries so ever here we have Chillicothe org which contains the which is the gfw website there are a few downloads here if you click this download button and we'll download the source code for gfw but instead we're
            • 04:00 - 04:30 going to go to download and you can see that we have precompiled binaries for Windows another great example here you can see for Linux and Mac OS you have to compile it yourself but for Windows we have these binaries now this brings us to our first question do I want 32-bit binaries or 64-bit binaries this has nothing to do with your actual operating system if you're running Windows 10 64 bit like I am that doesn't mean that you should be grabbing the 64-bit binaries what that means or like the way that you choose the ones you want is for your target for like for your application target so if I'm
            • 04:30 - 05:00 compiling my application as an x86 application as a win32 application then I would want the 32-bit binaries if I'm compiling a 64-bit application I was 64-bit binaries make sure you match them together because if you don't they won't link so in this case I'm going to just be making a 32-bit application so I'm going to grab the 32-bit Windows binaries and download them once I've downloaded and extracted them we'll have this folder over here inside there we have a bunch of folders and some other text files and this is kind of the typical layout like yes all the typical organizational structure that we have
            • 05:00 - 05:30 with libraries in C++ there are two parts to a library usually includes and libraries right so an include kind of directory and a library directory or a Lib directory so what the include directory is is a bunch of header files if you don't know how linking works in C bottles or what I even mean by link you check out the house if it was linking works video that I've made in the top right corner there it covers this stuff in depth but basically the include directory has a bunch of header files that we need to use so that we can actually use functions that are in the
            • 05:30 - 06:00 pre-built binaries and then the lint directory has those pre-built binaries and there are usually two phases to this right there's usually dynamic libraries and Static libraries not all libraries it's actually surprised not all libraries apply both of them for you jello W does though and you can choose if you want to link statically or dynamically we're going to talk a lot about the differences between static and dynamic linking in another video specifically about that but I'll cover the differences for you kind of simply here static linking means that the
            • 06:00 - 06:30 library actually gets basically put into your executable so just it's inside your DX a file or whatever your executable is for your operating system whereas a dynamic library gets actually linked at runtime so you still do have some kind of linkage you can choose to alert a dynamic library kind of just on the fly literally there's a function called load library which you can use in the Windows API as an example and that will load you like your dynamic library and you can pull function pointers out of data stalk calling functions away but you can also have a kind of at
            • 06:30 - 07:00 the application launch it loads your DLL file which is your dynamic link library and what I'm going to talk too much in depth about this but there's just that that difference of whether or not your library actually gets compiled into your exe file or links into your sa file and actually having a separate file for your library at runtime which you need to have alongside your Exe file or just somewhere so the UAA file can actually load that different stuff because of that kind of dependency of you now need to have a DLL file as well as your exa
            • 07:00 - 07:30 file usually I like to do static linking whenever possible static linking is also technically faster because the compiler or the link can actually perform kind of link time optimisation and all that stuff linking statically can technically result in a faster application because there are several optimizations that can be applied since we actually know the function that we're linking kind of add add actual about link time whereas with dynamic libraries we all know what's gonna happen we have to leave it intact and when the library actually gets bloated by our application of runtime that's one that parts kind of get
            • 07:30 - 08:00 patched up so usually static linking is the way to go but for this video I'm going to demonstrate both of those strategies so again we have the include files and then we have the library files to kind of components that we need is set up so for our compiler in our visual studio project we have to point it to the header files to the include file so that we actually know which functions we have available to us and so that we have those function declarations that really there's symbol declarations because they could also be variables I'm just using functions as an example and then we also
            • 08:00 - 08:30 have to point our linker to the library files and I'm waving my hands around love that that's just how I talks to deal with it and then we also need to tell our linker this is my library file I want you to link this so that we actually get the function definitions linked correctly let's go ahead and do that for both static and dynamic libraries so I bought this hollow world project here in Visual Studio it's very basic stuff but what I'm actually going to do is inside the solution directory make a folder called dependencies this is how I actually manage my dependencies in my libraries inside dependencies I'll
            • 08:30 - 09:00 make another folder called GFW and inside there I'm going to put the files that I actually downloaded which are the GLW library so include and live CC 2015 you can see here that they've actually appended kind of which compiled they used to actually compile this this library files form in gwgw 64 and then basically all these versions of Visual Studio will just pick the latest one it doesn't really matter in me at the end of the day they are just kind of compiled binaries and they will work with kind of either one but we want to use the one that's most compatible with
            • 09:00 - 09:30 our current tool chain which is BC 2015 because we're using video studio 2017 so I'll copy that and the include into this folder here include you can see has a gel FLV folder and then a bunch of paedophiles perfect and Lib has three files for us gow3 dll is the one time kind of dynamic link library that we actually use if we're linking dynamically at runtime and gow3 DLL dot Lib is actually kind of the static library that we use with the DLL so that
            • 09:30 - 10:00 we don't have to actually ask the DLL hey can I please have a bunch of function pointers to all of these functions the idea is that this Lib file actually contains all of the locations of the functions and symbols inside jela w3 DLL so that we can actually link against them at compile time so in comparison if we didn't have this Lib file we could still use this stuff how we have to ask the DLL file for each function by name and actually be like hey I want jillyfell B in it or whatever but this live file already kind of contains all of those locations for us so the linker can just link to them
            • 10:00 - 10:30 immediately gelatin b3 to live which you can see is significantly bigger than the other ones is the static library so this is what we linked if we don't want compile time linking and if we do that we don't need this DLL file to be without Exe file at runtime okay cool so let's actually link this stuff I'm going to right click on my hello world project hit properties and the first thing I'll actually do go to C C++ general and then in additional include directories I'm going to specify my additional include directory now note your configuration and platform make sure you're editing
            • 10:30 - 11:00 the right ones I obviously want this to apply for all configurations so I'll just hit all configurations now the include directory is the actual directory that goes each of this include folder so that's it I could just copy this directory but obviously you can see that it's in C uses yarn documents very specific to my computer if someone ends up cloning this from github or something like that they're not gonna have this path and that code isn't going to compile what I actually want to do is have a path that is relative to this actual directory so hollow world is the directory with my solution right
            • 11:00 - 11:30 everyone's going to have that if they check out my repository because this is my repository so inside it so starting from this solution file which I can do by typing in solution this is a macro that you can use in Visual Studio if I go under here into edit you can see that it actually evaluates to this value which is the solution directory if I hit macros over here I can see all of my macros and I can type in like solution de as an example and you can see what it is there's also things like project directory which is the directory of the
            • 11:30 - 12:00 project you can see that it's inside another hello world folder but the one that we care about it's virgin directory so we'll start off there and then we'll basically get that relative path which in this case is dependencies GL FW and include so I can just grab that and really just copy the end of that path starting in my solution directory folder I'll paste it into here hit enter and that's it I'm done what I can now do is basically just include files relative to this directory so this directory contains the GL FW folder
            • 12:00 - 12:30 which has a file called JAL it'll be three dot H so guess what I can do I can just come in here and type it include GL f w /j love w3 dot h just like that and that will actually work if I hit ctrl f7 to compile my code you can see that I get no errors now because this is a compiler specified in fluid path I can also use angular brackets and this kind of comes to the debate of do I use angular brackets or do I just use quotes Mike there's no difference because quotes will actually check the relative paths first and if it doesn't find
            • 12:30 - 13:00 anything relative to this file so relative to the main dot CPP file it will actually look for the compile it'll look through the compiler include parts now the way that I use this is basically if this source file is in Visual Studio so if gow3 or H is actually in in inside my solution somewhere maybe it's in a different project I don't care but it's inside this solution it's included in the solution then I will use quotes if it's an it's absolutely kind of external dependency or external library that isn't in I'm not compiling it with Visual Studio with
            • 13:00 - 13:30 this actual solution then I'll use angular brackets to kind of indicate that it's actually external so for this case I will write my code like this now I haven't actually linked against the libraries at all so I've told the compiler that hey there's a bunch of functions if I go to jail w3h you'll actually see that there's a bunch of stuff here I have a function for example called Jill up top you in it so let's try calling this over here my code I'll type in into a or something equals jail toluene is I don't know why my curly brackets a a black that is the worst idea ever I'm gonna fix that after this video
            • 13:30 - 14:00 anyway you can see that if I do gel 12 unit like this it looks like everything's fine I can hit ctrl f7 to compile my code you can see I don't get any compiler errors but of course if I try and actually build my project and run it all just hit build it's not gonna link correctly and you'll get an error that says unresolved external simple Jill it'll be eaten it this is the cause of so many problems for people what this means is that you haven't linked your actual library the linker can't find this jello double unit function if we actually go to the header
            • 14:00 - 14:30 file again and we take a look it's just got a semicolon here this doesn't tell us what the function actually does it just tells us that the function exists what we need to do is actually find a definition for that function now we could provide one I'll just show you I'm showing you this so that you know how it works so we know that U of W in here takes no parameters and returns an integer I could literally write chillip double unit here and it's like returns zero or something like that and then now if I build this and compile it you can see that it is going to successfully generate my hello world exe file and the build will succeed because
            • 14:30 - 15:00 I'm actually providing a definition for this function now obviously we don't want this definition we want the one that's actually in the library so we need to link against the library hopefully that clears things up so I'll right click on holo world hit properties to make sure again I'm in all configurations and on the right platform go to linker and in general now inside link input is where I actually want to include that chillip w3 don't live file right I actually want to include it over here however I don't want to have to
            • 15:00 - 15:30 specify the entire path so again I could do like you know solution directory slash blah blah I just want to keep this clean and just have we don't live here so if I want to do that I actually need to go back to general and set my additional library directory just like I did in C++ general with my additional include directory so this should be the root directory which contains my shell w3 don't live library file so I cannot go over here into my Java folder go back here to live and then this is the directory I care about so I'm going to grab this and copy it
            • 15:30 - 16:00 and then I'm going to come back to the library directories type in solution and then paste in that path just like that okay so I've specified a library directory and then I've also specify the name of a library file that is relative to that library directory so if I hit OK and I try and build this now you can see that this works fine and we don't actually get any errors and if I was to for example run this let's just print the result of this to the console here 5 you can see that we actually get one
            • 16:00 - 16:30 printing here which basically means that you'll have W initialized successfully so everything is working fine now similarly to how I showed you how I actually manually added a G lfwe th function definition the same kind of applies for a header file right if I get rid of this include or I don't have my header files I just don't know that there's a function called G let's all be eating it actually available if I try and compile this code it's not it's not that it's not gonna link it's just not gonna compile because there is no such function the compiler can't see a function called shelf double-unit however if I provide the actual
            • 16:30 - 17:00 declaration here by typing in G left I'll be eating it and just returning nothing like that and hit f5 to run my code the idea of this will actually work however in this specific case we get an error because G of W is actually a C library and what we're doing here is mangling the name with C++ I'll have a video is specifically about kind of using C with C + + + name mangling and actually what's going on here but to cut this short we need to actually add extern C to this function declaration which basically just says that preserve
            • 17:00 - 17:30 this name as it is because you'll be linking against a library that was built in C so now if we compile this code you can see that it works successfully and if I run it as well we still get one same result that we got when we had the header file so just remember those header files are kind of just best that you have to do this stuff yourself it's not like the library linking is magically includes the magic or anything like that it's just all components of a system to kind of go together so the header files kind of just tell us which functions we have available by providing us with declarations and then that library file provides us with
            • 17:30 - 18:00 definitions so that we actually can link to those functions and execute the appropriate code when we call the functions in our C++ code okay I'm gonna wrap up the video there I know we did talk about dynamic libraries but this video is just been trailing I actually thought this would be pretty trivial to explain and it would take like five minutes but as always I've just gone pretty in-depth and just talked about this a lot which i think is a good thing we're gonna talk about dynamic libraries in another video though and specifically with that I'll show you how to also kind of pull them out if you don't have a static library to go along with them like we do with yellow to view some otherwise I'll show
            • 18:00 - 18:30 you how to pull out functions and do all that kind of actual runtime linking as well as linking against an actual DL but at compile time as well because there's a few kind of caveats with that as well I hope you guys enjoy this video if you did you can have that like button you can also help support the series on patreon we're going to patreon.com/scishow know you'll get episodes earlier there are some pretty cool new perks as well which you should check out I will see you guys next time goodbye [Music]