编译C++代码提示isPrime(int)未定义引用,求排查解决
Let's work through your problem step by step—first fixing the linker error, then addressing the logic bugs in your code:
1. Resolving the Undefined Reference Error
That linker error means the compiler can't find the compiled implementation of your isPrime function, even though you've declared it in the header. Let's rule out simple issues first:
Double-check your compilation command matches exactly what you ran:
g++ -o main main.cpp extFunc.cppMake sure your filenames are case-sensitive (Linux/macOS care about this—so
extFunc.cppisn't accidentallyExtFunc.cpporextfunc.cpp) and both files are in the same directory when you run the command.If the error persists, try compiling in separate steps to isolate where things go wrong:
# Compile extFunc.cpp to an object file g++ -c extFunc.cpp # Compile main.cpp to an object file g++ -c main.cpp # Link both into the final executable g++ -o main main.o extFunc.oThis will show you if either file has a hidden compilation error that's preventing the linker from finding the function.
2. Fixing Critical Bugs in isPrime
Even if you fix the linker error, your isPrime function has logic flaws that will make it behave incorrectly:
- You're using assignment (
=) instead of equality comparison (==) in all yourifchecks. This means you're overwriting the inputnuminstead of testing its value—completely breaking your logic. - Your unstructured
ifblocks will overwrite thenumPrimevariable even after a valid check. Useelse ifto chain conditions properly. - The final
if (numPrime == true)check is redundant—you can just return the boolean directly.
Here's the corrected extFunc.cpp:
#include "extFunc.h" bool isPrime(int num) { // Handle edge cases upfront if (num <= 1) { return false; } if (num == 2 || num == 3) { return true; } // Check divisibility up to sqrt(num) for better efficiency for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true; }
3. Fixing the Bug in main.cpp
Your main function has the same assignment-vs-comparison bug in the final check:
// Wrong: assigns true to prime, so this will always run if (prime = true) // Correct: checks if prime is true if (prime == true) // Even cleaner: use the boolean directly if (prime)
4. Adding Header Guards (Good Practice)
While this wasn't causing your linker error, adding header guards to extFunc.h prevents duplicate declaration errors if the header is included multiple times:
#ifndef EXTFUNC_H #define EXTFUNC_H bool isPrime(int num); #endif // EXTFUNC_H
After making these changes, recompile with your original command and everything should work as expected.
内容的提问来源于stack exchange,提问作者Longji Kang

