Search code examples
cvisual-studio-codecompilationcs50

Why do I need to use gcc -o string string.c cs50.c to compile?


When I was starting to learn C in cs50 course, I had a trouble when running the get_string function. It gave me an error saying get_string is undefined. I solved the error by using gcc -o string string.c cs50.c in the vscode terminal and then running it. My doubt is "why can't i use the run (F5)".

I am a total beginner in C.


Solution

  • In the CS50 course, the get_string function is provided by the CS50 library, which is a custom library created specifically for the course. When you compile your C program using the gcc command with the flag -o and with both files, it links your code with the CS50 library and creates an executable file.

    When you use the run button on Visual Studio Code or F5, it typically runs the program directly without any additional compilation or linking steps. Since the CS50 library is not automatically linked when using the "run" option, the compiler is unable to find the definition of the get_string function, resulting in an error.

    By manually compiling and linking your code using the gcc you explicitly include the CS50 library, allowing the get_string function to be resolved correctly during the linking process. This is why you were able to solve the error by using the command gcc -o string string.c cs50.c in the VSCode terminal.