Append -lm to the end of your gcc command.

With all recent versions of GCC on GNU/Linux systems like Ubuntu, when you use the math library, you have to explicitly link to it. It is not automatically linked to along with the rest of the standard C library.

If you are compiling on the command-line with the gcc or g++ command, you would accomplish this by putting -lm at the end of the command.

For example: gcc -o foo foo.c -lm

Answer from Eliah Kagan on askubuntu.com
Top answer
1 of 2
70

The problem is coming from the linker, ld, rather than gcc (hence the exit status message). In general ld requires objects and libraries to be specified in the order user supplier, where user is an object that uses a library function and supplier is the object which provides it.

When your test.c is compiled to an object the compiler states that fmod is an undefined reference

$ gcc -c test.c
$ nm test.o
                 U fmod
0000000000000000 T main

(nm lists all the functions referred to by an object file)

The linker changes the undefined references to defined ones, looking up the references to see if they are supplied in other files.

$ gcc -lm test.o
$ nm a.out
0000000000600e30 d _DYNAMIC
0000000000600fe8 d _GLOBAL_OFFSET_TABLE_
00000000004006a8 R _IO_stdin_used
                 w _Jv_RegisterClasses
0000000000600e10 d __CTOR_END__
...
0000000000601018 D __dso_handle
                 w __gmon_start__
...
                 U __libc_start_main@@GLIBC_2.2.5
0000000000601020 A _edata
0000000000601030 A _end
0000000000400698 T _fini
0000000000400448 T _init
0000000000400490 T _start
00000000004004bc t call_gmon_start
0000000000601020 b completed.7382
0000000000601010 W data_start
0000000000601028 b dtor_idx.7384
                 U fmod@@GLIBC_2.2.5
0000000000400550 t frame_dummy
0000000000400574 T main

Most of these refer to libc functions that are run before and after main to set the environment up. You can see that fmod now points to glibc, where it will be resolved by the shared library system.

My system is set up to use shared libraries by default. If I instead force static linking I get the order dependency you see

$ gcc -static -lm test.o
test.o: In function `main':
test.c:(.text+0x40): undefined reference to `fmod'
collect2: ld returned 1 exit status

Putting -lm later in the linker command, after test.o, allows it to link successfully. Checking the symbols fmod should now be resolved to an actual address, and indeed it is

$ gcc -static test.o -lm
$ nm a.out | grep fmod
0000000000400480 T __fmod
0000000000402b80 T __ieee754_fmod
0000000000400480 W fmod
2 of 2
6

From the gcc(1) manpage: "the placement of the -l option is significant."

Specifically:

   -llibrary
   -l library
       Search the library named library when linking.  (The second alternative with the library as a
       separate argument is only for POSIX compliance and is not recommended.)

       It makes a difference where in the command you write this option; the linker searches and processes
       libraries and object files in the order they are specified.  Thus, foo.o -lz bar.o searches library z
       after file foo.o but before bar.o.  If bar.o refers to functions in z, those functions may not be
       loaded.

       The linker searches a standard list of directories for the library, which is actually a file named
       liblibrary.a.  The linker then uses this file as if it had been specified precisely by name.

       The directories searched include several standard system directories plus any that you specify with
       -L.

       Normally the files found this way are library files---archive files whose members are object files.
       The linker handles an archive file by scanning through it for members which define symbols that have
       so far been referenced but not defined.  But if the file that is found is an ordinary object file, it
       is linked in the usual fashion.  The only difference between using an -l option and specifying a file
       name is that -l surrounds library with lib and .a and searches several directories.
🌐
Medium
medium.com › @larmalade › gcc-the-hard-way-how-to-include-functions-from-the-math-library-1cfe60f24a7a
gcc The Hard Way: How to Include Functions from the Math Library | by Larry Madeo | Medium
February 12, 2017 - Even today, in the age of hand-held supercomputers, we add the -lmflag to the gcc command in order to include<math.h> which is necessary to use the floating point math functions available in the standard C library.
🌐
W3Schools
w3schools.com › c › c_ref_math.php
C math (math.h) Library Reference
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... The <math.h> library has many functions that allow you to perform mathematical tasks on numbers.
🌐
GitHub
gist.github.com › 2759457
gcc #include <math.h>
Clone this repository at &lt;script src=&quot;https://gist.github.com/underhilllabs/2759457.js&quot;&gt;&lt;/script&gt; Save underhilllabs/2759457 to your computer and use it in GitHub Desktop. Download ZIP · gcc #include <math.h> Raw · include_math.md · gcc faq · 14.3: I'm trying to do some simple trig, and I am #including <math.h>, but I keep getting "undefined: sin" compilation errors.
🌐
GNU
gnu.org › software › libc › manual › html_node › Mathematics.html
Mathematics (The GNU C Library)
This chapter contains information about functions for performing mathematical computations, such as trigonometric functions. Most of these functions have prototypes declared in the header file math.h.
Find elsewhere
🌐
Reddit
reddit.com › r/c_programming › math.h library doesn't compile on linux (even when compiling with -lm)
r/C_Programming on Reddit: math.h library doesn't compile on linux (even when compiling with -lm)
May 11, 2024 -

I'm studying C programming for an exam at my university, and since we will take the exam on computers using Linux Debian our teachers have told us to install a Debian virtual machine (Oracle VM Virtualbox) to practice.
I use geany to code and I have to use the math.h library sometimes. I know in order to do that i need to compile with gcc -lm but it doesn't seem to work. Can anyone help me?

The command I used on the terminal is:

gcc -lm 2_razzo_parte_opzionale.c

The error that shows up on the shell is:

/usr/bin/ld: /tmp/cceZf8ZJ.o: in function ˋriempi_array': 2_razzo_parte_opzionale.c:(.text+0x2fc): undefined reference to ˋpow'
/usr/bin/ld: 2_razzo_parte_opzionale.c:(.text+0x3ee): undefined reference to ˋlog'
collect2: error: ld returned 1 exit status

If it is useful in any way, this is the code i wrote:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void ask_parametri(double *m_in, double *tasso_esp, double *vel_esp){
  int count=0;

  printf("Richiesta dei parametri\n"); printf("\n");

  do {  if(count!=0){printf("Errore: inserire un valore maggiore di 0\n");}
        else{}
    printf("Inserire la massa iniziale di carburante (>0) [kg]: ");
    scanf("%lf",m_in);
    count++;
  }while(*m_in<=0);printf("\n"); count=0;

  do {  if(count!=0){printf("Errore: inserire un valore maggiore di 0\n");}
        else{}
   printf("Inserire il tasso di espulsione del carburante (>0) [kg/s]: ");
   scanf("%lf",tasso_esp);
   count++;
  }while(*tasso_esp<=0);printf("\n"); count=0;

  do {  if(count!=0){printf("Errore: inserire un valore maggiore di 0\n");}
        else{}
   printf("Inserire la velocità di espulsione del carburante (>0) [m/s]: ");
   scanf("%lf",vel_esp);
   count++;
  }while(*vel_esp<=0);printf("\n");
}

void ask_intervallo(double *t_f, double t_max){
  int count=0;

  do{if(count!=0){printf("Errore: inserire un valore minore di %lf\n",t_max);}
  else{}

    printf("Inserire la lunghezza dell'intervallo di tempo in esame [s]: ");
    scanf("%lf",t_f);
    count++;
  }while(t_max<=*t_f);printf("\n");
}
 
int ask_step(){
  int n, count=0;
  do{  if(count!=0){printf("Errore: inserire un valore maggiore di 0\n");}
        else{}
    printf("Quanti campionamenti si vogliono? ");
    scanf("%d",&n);
    count++;
  }while(n<=0);printf("\n");
return n;}

void riempi_array(double *t, double *m, double *v, int n, double t_f, double m_0, double m_punto, double w){
  int i;
  double dt, k=0.5;
  t[0]=0;
  m[0]=m_0;
  v[0]=0;
  dt=t_f*(1-k)/(1-pow(k,n));

  for(i=1;i<=n;i++){
  dt=k*dt;
  t[i]=t[i-1]+dt;
  m[i]=m_0-m_punto*t[i];
  v[i]=-w*log(m[i]/m_0);
  }
}

void grafico(char *file, double *t, double *m,double *v,int n){
  FILE *fp;
  fp=fopen(file,"w");
  
  int i;
  for(i=0;i<=n;i++){
    fprintf(fp,"%lf %lf %lf\n",t[i],m[i],v[i]);
  }
  fclose(fp);
  }

int main(){
  double m0,m_punto,v_esp, t_0, t_max;
  int n_step;
  double *m_0=&m0, *dm_dt=&m_punto, *w=&v_esp, *t_finale=&t_0;
  double *t;
  double *m;
  double *v;
  
  ask_parametri(m_0,dm_dt,w);
  
  t_max=m0/m_punto;
  
  ask_intervallo(t_finale,t_max);
  
  n_step=ask_step();
  
  t= (double *) calloc(n_step+1,sizeof(double));
  m= (double *) calloc(n_step+1,sizeof(double));
  v= (double *) calloc(n_step+1,sizeof(double));
  
  riempi_array(t,m,v,n_step,t_0,m0,m_punto,v_esp);
  
  grafico("razzo2.dat",t,m,v,n_step);
return 0;}
🌐
Stanford CCRMA
ccrma.stanford.edu › courses › 250a-fall-2002 › docs › avrgcc › math_8h-source.html
math.h Source File
math.h - mathematical functions 00003 · 00004 · Author : Michael Stumpf 00005 · Michael.Stumpf@t-online.de 00006 · 00007 · __ATTR_CONST__ added by marekm@linux.org.pl for functions 00008 · that "do not examine any values except their arguments, and have 00009 · no effects except the return value", for better optimization by gcc.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › c-library-math-h-functions
C Library math.h Functions - GeeksforGeeks
April 3, 2023 - #include <math.h> #include <stdio.h> int main() { float val1, val2, val3, val4; val1 = 1.6; val2 = 1.2; val3 = -2.8; val4 = -2.3; printf("value1 = %.1lf\n", ceil(val1)); printf("value2 = %.1lf\n", ceil(val2)); printf("value3 = %.1lf\n", ceil(val3)); printf("value4 = %.1lf\n", ceil(val4)); return (0); }
🌐
Reddit
reddit.com › r/programminghelp › how to link math.h using makefile for gcc
r/programminghelp on Reddit: How to link math.h using makefile for gcc
September 3, 2020 -
CC = gcc
CFLAGS = -O

default: run

run: build
	run < program.cs 
build: compile
	$(CC) -o run main.o closed_hashtable.o 
compile: main.c closed_hashtable.c closed_hashtable.h 
	$(CC) -c main.c 
	$(CC) -c closed_hashtable.c 
clean:
	$(RM) *.o *.gch

How do I link math.h using the makefile above?

🌐
Super User
superuser.com › questions › 977602 › intel-icc-breaks-gcc-with-math-h-on-linux
symbolic link - Intel icc breaks gcc with math.h on linux - Super User
Normally I have to link to the math.h library with -lm, and this works with other files. The other cases I've tested do not include mpi.h, if it matters. I don't care to uninstall the intel compilers; I was hoping to fix whatever problems I have locally before moving to working remotely via ssh. ... I ran gcc fvm.c -c --trace -lm to see where it was looking for the math library.
🌐
GNU
gcc.gnu.org › onlinedocs › libstdc++ › libstdc++-html-USERS-4.3 › a01932.html
libstdc++: math.h Source File
March 26, 2008 - 00032 */ 00033 00034 #ifndef _GLIBCXX_TR1_MATH_H 00035 #define _GLIBCXX_TR1_MATH_H 1 00036 00037 #include <tr1/cmath> 00038 00039 #if _GLIBCXX_USE_C99_MATH_TR1 00040 00041 using std::tr1::acos; 00042 using std::tr1::acosh; 00043 using std::tr1::asin; 00044 using std::tr1::asinh; 00045 using ...
🌐
Carnegie Mellon University
cs.cmu.edu › ~jh6p › classes › studio › gcc-2.5.8 › include › math.h
math.h
*/ #ifndef __math_h #ifdef __cplusplus extern "C" { #endif #ifndef _PARAMS #if defined(__STDC__) || defined(__cplusplus) #define _PARAMS(ARGS) ARGS #else #define _PARAMS(ARGS) () #endif #endif /* _PARAMS */ #define __math_h /* * Posix (actually ansi C) section */ #ifndef HUGE_VAL #define HUGE_VAL (__infinity()) /* Produces IEEE Infinity.
🌐
GitLab
gitlab.redox-os.org › yifan an › gcc › repository
libstdc++-v3/include/c_compatibility/math.h · gcc-4_4_2-release · Yifan An / gcc · GitLab
// a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see · // <http://www.gnu.org/licenses/>. /** @file math.h · * This is a Standard C++ Library header. */ #include <cmath> #ifndef _GLIBCXX_MATH_H ·
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 178740-clarification-regarding-linking-libraries-using-gcc.html
Clarification regarding linking libraries using gcc
February 9, 2020 - The standard library header files such as stdio.h, string.h, stdlib.h etc are all resolved by libc, and the compiler automatically uses that. Historically, the math library was separate because all floating point was done in software. If you didn't use FP, then there was no need to pay a price.
🌐
Unix Community
community.unix.com › solaris
GCC 9.2 math.h misuse in favor of /usr/include one - Solaris - Unix Linux Community
December 31, 2019 - I downloaded GCC 9.2.0 from ... compile in C++ it simply cannot, telling that things arent defined in /usr/include/math.h, however, while the math.h in GCC 9.2 directory is different to the one in /usr/include, Solaris use the /usr/include one instead of the gcc 9.2 one, ...
🌐
Intel
intel.com › content › www › us › en › docs › dpcpp-cpp-compiler › developer-guide-reference › 2023-1 › intel-oneapi-dpc-c-compiler-math-library.html
Intel® oneAPI DPC++/C++ Compiler Math Library
Intel's math.h header file is compatible with the GCC Math Library libm, but it does not cause the GCC Math Library to be linked. The source can be built with gcc or icx. The header file for the math library, mathimf.h, contains additional functions ...
🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › unixhelp › debuggingtips_C.html
Debugging
For example, if you are calling the sqrt function from the math library, you need to include the math.h header file in your .C file and you need to explicitly link the math library into your executable: gcc -g -Wall -o myprog myprog.o -lm ^^^ Most libraries are in /usr/lib/. If not, you may need to include the -L option to gcc to tell it where to find your library.