D
D
DVoropaev2017-08-29 10:26:52
C++ / C#
DVoropaev, 2017-08-29 10:26:52

Why is it not connected to gcc?

Here is my code:

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



double time(float x){
  return 5.0*sqrt(x*x + 36.0) + 4.0*(20.0 - x);
}

int main(){
  double l = 0;
  double r = 20;
  for(int i = 0; i < 1000; i++){
    double mid = (r+l)/2;
    double tl = mid - mid/10;
    double tr = mid + mid/10;
    if(time(tl) < time(tr))
      r = tr;
    else
      l = tl;
  }
  printf("x = %g;  t = %g\n", (l+r)/2, time((l+r)/2));
  return 0;
}

When compiled, it produces this:
$ gcc ./cro.c
/tmp/ccqtObxh.o: In function `time':
cro.c:(.text+0x28): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

However, if you specify the '-lm' option, then everything is compiled.
Why is this option needed? what she does? why is it not enough to just write #include?
And if I have 10 libraries connected, should I write some option for each?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Movchan, 2017-08-29
@Alexander1705

Library != header file.
The header file contains only declarations (ie descriptions). For example:

// time.h
#ifndef TIME_H
#define TIME_H
double time(float x);
#endif

The implementation may be in a separate file.
// time.c
#include "time.h"
#include <math.h>

double time(float x){
  return 5.0*sqrt(x*x + 36.0) + 4.0*(20.0 - x);
}

In order not to compile this code every time, you can compile it once into a library:
gcc -c time.c -o time.o # Создаём объектный файл (скомпилированый код)
ar rcs libtime.a time.o # Создаём статическую библиотеку (по сути, архив объектных файлов)

And then just connect it:
// main.c
#include <stdio.h>
#include <math.h>
#include "time.h"

int main(){
  double l = 0;
  double r = 20;
  for(int i = 0; i < 1000; i++){
    double mid = (r+l)/2;
    double tl = mid - mid/10;
    double tr = mid + mid/10;
    if(time(tl) < time(tr))
      r = tr;
    else
      l = tl;
  }
  printf("x = %g;  t = %g\n", (l+r)/2, time((l+r)/2));
  return 0;
}

PS -l is short for link.
PPS Separation of libc and libm has developed for historical reasons.

R
res2001, 2017-08-29
@res2001

Probably because in gcc mathematical functions are moved to a separate library - libm.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question