为什么需要使用`gcc -o string string.c cs50.c`来编译?

huangapple go评论59阅读模式
英文:

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

问题

当我开始学习cs50课程中的C语言时,运行get_string函数时遇到了麻烦。它给出了一个错误,说“get_string未定义”。我通过在VSCode终端中使用gcc -o string string.c cs50.c来解决了这个错误,然后运行它。我的疑问是,“为什么我不能使用运行(F5)”。我是一个完全的C语言初学者。

英文:

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.

答案1

得分: 3

在CS50课程中,get_string函数由CS50库提供,这是专门为该课程创建的自定义库。当你使用gcc命令编译你的C程序,并使用标志-o以及两个文件时,它会将你的代码与CS50库链接在一起,并创建一个可执行文件。

当你在Visual Studio Code上使用run按钮或按下F5时,通常会直接运行程序,无需额外的编译或链接步骤。由于在使用“run”选项时CS50库不会自动链接,编译器无法找到get_string函数的定义,从而导致错误。

通过手动使用gcc编译和链接你的代码,你可以显式地包含CS50库,允许在链接过程中正确解析get_string函数。这就是为什么你可以通过在VSCode终端中使用命令gcc -o string string.c cs50.c来解决错误的原因。

英文:

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.

huangapple
  • 本文由 发表于 2023年6月19日 13:15:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定