编译C代码出现undefined reference错误的原因及解决方法咨询
Alright, let's break down this error and fix it for you.
Why does this error happen?
This is a linker error, not a compiler error. Here's the breakdown:
- You correctly included
myLibrary.h, so the compiler recognizedfunction1()exists (thanks to the function declaration in the header) and didn't throw a compile-time issue. - But when the linker tried to assemble the final executable, it couldn't find the actual implementation of
function1—the code you wrote inmyLibrary.c. This is because you only compiled your main.cfile (I'm assuming it's02_01.c) and didn't includemyLibrary.cin the full compilation/linking workflow.
Fixes to resolve the undefined reference
1. Compiling via command line (MinGW/GCC)
When using gcc, you need to pass all the .c files that make up your program. Instead of running just:
gcc 02_01.c -o myProgram.exe
Use this command instead:
gcc 02_01.c myLibrary.c -o myProgram.exe
This tells GCC to compile both .c files into object files first, then link them together—so the linker can locate function1's code.
2. Using an IDE (like Code::Blocks, Dev-C++, etc.)
- Make sure
myLibrary.cis added to your project, not just sitting in the same folder as your main file. - IDEs only compile files listed in the project structure. If
myLibrary.cisn't in that list, the linker will never access its function implementations.
A quick side note: Your #define MAX_LENGTH 21.8 defines a float value as a macro—just be cautious if you use this in contexts expecting an integer later, but this isn't related to your current linker error.
内容的提问来源于stack exchange,提问作者packagemover
相关产品推荐
相关产品推荐

