Coding⏱️ 2 min read📅 2026-06-03

How to Fix: Why am I getting "undefined reference to sqrt" error even though I include math.h header?

undefined reference to sqrt error due to missing library linkage.

Quick Answer: The issue is that the math.h header only declares the sqrt function, but does not provide its implementation. To fix this, you need to link against the math library when compiling with gcc.

The `undefined reference to sqrt` error occurs when the linker is unable to find the definition of the `sqrt` function. This is not due to a missing inclusion of the `math.h` header, but rather because the compiler is unable to link against the math library.

🛑 Root Causes of the Error

  • The `math.h` header file only declares the `sqrt` function, but does not define it. The definition is provided by the math library.

🛠️ Step-by-Step Verified Fixes

Method 1: Linking Against the Math Library

  1. Step 1: Add the `-lm` flag to the compiler command when linking. This will link against the math library.

Method 2: Using `#include `

  1. Step 1: Replace `` with `` in the include statement. This will use the C++ implementation of the math library.

💡 Conclusion

By adding the `-lm` flag or using ``, you can resolve the `undefined reference to sqrt` error and successfully compile your code.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions