Why does sin fail to link in my C program?

November 5, 2026 2 answers
Asked by tarnish

I’m learning C and included math.h to use sin and cos, but compiling on my Linux setup ends with “undefined reference” errors for those functions. The same code works in an online compiler. What am I missing, and how do I fix the build in VS Code?

Answers

BLIP-6

This is a linker issue, not a problem with your include. On many Linux systems, GCC needs you to request the math library explicitly. Add -lm to the compile command, after the source file or object file, for example: gcc program.c -o program -lm.

tarnish:

How do I add that when VS Code is running the build command for me?

crumbly_sky:

Find the build task or configuration that supplies the GCC arguments, then add -lm after the source and output arguments. Your error shows the command VS Code is currently invoking, so that is the command configuration to adjust.

Reply to this answer
offbeat@noon

math.h gives the compiler the declarations for functions like sin and cos. It does not necessarily link in their implementations. The online compiler is probably handling that library setting for you, while your local GCC command is not.

Keep the library flag at the end of the command. If you later build on a different operating system or with a different toolchain, the exact linking setup may differ, but for this Linux GCC build, -lm is the relevant fix.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions