Undefined reference to sin linux

Undefined reference to `sin’ when passing variable instead of constant [duplicate]

I had a code that was working perfectly in windows but when i tried to compile it in linux i got an error. I found that the issue is with the sin() function. If i pass to it a constant number directly, it works fine:

#include #include int main(void)
#include #include int main(void)
/tmp/ccfFXUZS.o: In function `main': source-bcfaa9ff162b:(.text+0x1a): undefined reference to `sin' collect2: error: ld returned 1 exit status 

You probably aren’t linking the math library and in your first example the compiler probably calculated the value for you (it’s constant). Putting that variable in probably results in a call to sin .

sin expects a double. In your first snippet you pass a double, in your second one you pass a float. If you have a lot of warnings enabled or perhaps if you compile C as C++, that might be an issue.

2 Answers 2

On some systems, the math functions are in a separate library, which needs to be linked explicitly. Simply pass the option -lm when compiling (linking) your program, and everything should work.

The reason the first one works is because the compiler knows about sin and optimized the whole thing to a constant — it doesn’t need to actually call the sin function.

@rullof: The error has nothing to do with datatypes; it’s the compiler telling you it can’t find the code for the sin function (which it wants to use because it just sees a variable as the argument).

@rullof: Look carefully at the compiler selection: You’re compiling the one with double as C++ code. Your failing example is compiling as C code — and this is enough to change things. If you compile your double version as C code, it fails in the exact same way as the float version.

Источник

С каких пор gcc требует линковать с мат либой при использовании ?

Чет всегда компилилось норм, а сегодня стандартная фигня типа:

Требует чтобы я при компиляции указывал -lm

Ну наверно ты компилял раньше c++, а теперь c

Не знаю, когда он этого не требовал, но одной из причин неведения может быть использование builtin реализаций и/или макросов, тогда и без библиотеки может работать.

вообще всегда требовал, но иногда бывало что работало без -lm. видимо, в некоторых версиях gcc / настройках компиляции / оптимизации, подтаскиваются builtin, и тогда -lm не нужен.

Читайте также:  Astra linux дублирование экрана

было бы тоже интересно узнать точную причину, почему иногда без -lm код собирается и работает.

С каких пор gcc требует линковать с мат либой при использовании ?

 pony cat pony.c #include #include int main(void) < int i; for (i = 0; i < 64; i++) < printf("%f\n", sin(i + 1)); >return 0; > ➜ pony cat pony.cpp #include #include int main(void) < int i; for (i = 0; i < 64; i++) < std::cout return 0; > ➜ pony gcc pony.c /tmp/cc6V89tE.o: In function `main': pony.c:(.text+0x20): undefined reference to `sin' collect2: error: ld returned 1 exit status ➜ pony g++ pony.cpp ➜ pony 

В СИшном около всегда надо было линковать math

fornlr ★★★★★ ( 20.10.16 16:20:03 MSK )
Последнее исправление: fornlr 20.10.16 16:21:08 MSK (всего исправлений: 1)

alex@alex:~/Проекты/test/md5$ cat ./prony.c #include #include int main(void) < printf("%f\n", sin(1)); return 0; >alex@alex:~/Проекты/test/md5$ gcc prony.c -o prony.c alex@alex:~/Проекты/test/md5$ ./prony 0.841471 

Может компилятор оптимизирует это до константы и потому библиотеку не требует. Ты переменную подставь

Может компилятор оптимизирует это до константы и потому библиотеку не требует

Если так, я буду нереально удивлен. А может дело в его системе сборки? Например, qmake вероятно может что-то своего подпихнуть, в том числе -lm

где ты видишь систему сборки в его сообщении?

Источник

Math library linking error in CLion on Linux [duplicate]

To do my homework I need #include «math.h» , but after updating GCC and CMake, CLion can’t link my project files. What should I do to fix this problem? In Settings -> Build, Execution and Deployment -> Toolchains CLion says that CMake version is 3.15.3 and GDB version is 8.3 and it’s OK. I already tired to reinstall GCC, CMake and CLion, but it didn’t work. Also I tired to search some info on StackOverflow, but still nothing works. Main.c:

#include #include int main() < FILE *output; output = fopen("/home/vadimsam/CLionProjects/untitled/data.txt", "w"); double x=0.,v=0.,t=0.,m=0.,k=0.,dt = 1e-5,xn,vn; while (t < 1e1) < vn = -x*sqrt((k/m))*cos(sqrt((k/m))*t)+v*cos(sqrt((k/m))*t); xn = -x*cos(sqrt((k/m))*t)+(v/sqrt((k/m)))*sin(sqrt((k/m))*t); t += dt; x = xn; v = vn; fprintf(output, "%lf %lf %lf\n", t, x, v); >fclose(output); return 0; > 
cmake_minimum_required(VERSION 3.15) project(untitled2 C) set(CMAKE_C_STANDARD 11) add_executable(untitled2 main.c) 
====================[ Build | untitled2 | Debug ]=============================== /home/vadimsam/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5096.27/bin/cmake/linux/bin/cmake --build /home/vadimsam/CLionProjects/untitled2/cmake-build-debug --target untitled2 -- -j 8 Scanning dependencies of target untitled2 [ 50%] Building C object CMakeFiles/untitled2.dir/main.c.o [100%] Linking C executable untitled2 CMakeFiles/untitled2.dir/main.c.o: In function `main': /home/vadimsam/CLionProjects/untitled2/main.c:10: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:10: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:10: undefined reference to `cos' /home/vadimsam/CLionProjects/untitled2/main.c:10: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:10: undefined reference to `cos' /home/vadimsam/CLionProjects/untitled2/main.c:11: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:11: undefined reference to `cos' /home/vadimsam/CLionProjects/untitled2/main.c:11: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:11: undefined reference to `sqrt' /home/vadimsam/CLionProjects/untitled2/main.c:11: undefined reference to `sin' collect2: error: ld returned 1 exit status CMakeFiles/untitled2.dir/build.make:83: recipe for target 'untitled2' failed make[3]: *** [untitled2] Error 1 CMakeFiles/Makefile2:75: recipe for target 'CMakeFiles/untitled2.dir/all' failed make[2]: *** [CMakeFiles/untitled2.dir/all] Error 2 CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/untitled2.dir/rule' failed make[1]: *** [CMakeFiles/untitled2.dir/rule] Error 2 Makefile:118: recipe for target 'untitled2' failed make: *** [untitled2] Error 2 

Источник

Читайте также:  What is pci device in linux

unixforum.org

получается что функция синуса sin() не определена в хотя документация говорит обратное.
Уважаемые кодеры помогите разобраться в чем собака зарыта вроде все просто.
Спасибо
PS я так понимаю когда я пишу #include то подключается файл /usr/include/math.h открыл его в редакторе дак там обявлений упомянутых функций нет вообще.

S7a1k3r Сообщения: 159 Статус: Белгородский LUG ОС: Arch Linux Контактная информация:

Re: Немогу вызвать sin() из библиотеки

Сообщение S7a1k3r » 14.06.2008 23:11

#ifdef HAVE_CONFIG_H #include #endif #include #include #include int main(int argc, char *argv[]) < int i=1; double stel=0; for (;i<10000000;i++) < stel+=sin(i/1000000.); >printf("%f",stel); return EXIT_SUCCESS; >
/home/Razor/kdeveloop/huh/src/huh.c:42: undefined reference to `sin'

получается что функция синуса sin() не определена в хотя документация говорит обратное.
Уважаемые кодеры помогите разобраться в чем собака зарыта вроде все просто.
Спасибо
PS я так понимаю когда я пишу #include то подключается файл /usr/include/math.h открыл его в редакторе дак там обявлений упомянутых функций нет вообще.

Re: Немогу вызвать sin() из библиотеки

Сообщение Iroln » 14.06.2008 23:18

Для использования математической библиотеки используйте вызов компилятора с ключом -lm

Re: Немогу вызвать sin() из библиотеки

Сообщение FoRtNoX » 14.06.2008 23:23

Попробуй скомпилировать с аргументом -lm
Компилятор просто не может найти math.h — вот и выдает ошибку

uptime Сообщения: 1661 Статус: Drinker with computing problems ОС: kubuntu 8.04

Re: Немогу вызвать sin() из библиотеки

Сообщение uptime » 14.06.2008 23:37

/home/Razor/kdeveloop/huh/src/huh.c:42: undefined reference to `sin'

получается что функция синуса sin() не определена в хотя документация говорит обратное.
Уважаемые кодеры помогите разобраться в чем собака зарыта вроде все просто.
Спасибо
PS я так понимаю когда я пишу #include то подключается файл /usr/include/math.h открыл его в редакторе дак там обявлений упомянутых функций нет вообще.

Посмотрел. math.h подключает инклудом bits/mathcalls.h, который уже и содержит объявление sin. Объявления функций используются компилятором для проверки типов аргументов и возвращаемого значения.
Но в вашем случае дело не в отсутствии объявления, а в отсутствии самой функции. Как, впрочем, уже было сказано выше.

Re: Немогу вызвать sin() из библиотеки

Сообщение mih-vik » 01.11.2014 13:08

Прочел с большим интересом, т.к. никогда в сишных модулях математика не нужна была, и вдруг как всегда срочно, а оно не линкуется, в общем все знают.
Перепробовал в спешке все перечисленное, на моей юбунте катит, если тупо ставить ключ -lm в конце команды вызова, не важно чего — gcc, cc или ld, напр
gcc neuro1.c -lm //получаем a.out
gcc -c neuro1.c // получаем neuro1.o, а затем линкуем его
gcc -o neuro neuro1.o -lm // получаем исполняемый neuro
ЗЫ. Это не спам, а для тех торопыжливых, кому некогда читать все (хотя прочесть — так польза большая будет))))

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Читайте также:  Change iptables on linux

Источник

Undefined reference to `sin` [duplicate]

However, I’ve written various test programs that call sin from within the main function, and those work perfectly. I must be doing something obviously wrong here — but what is it?

4 Answers 4

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add » -lm » to link with the math library in the step where you are attempting to generate your executable.

Why for sin() in , do we need -lm option explicitly; but, not for printf() in ?

Because both these functions are implemented as part of the «Single UNIX Specification». This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on «POSIX compliant systems» in order to reach more platforms.
  5. UNIX customers demanded «POSIX compliant» UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don’t use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that’s why you must add -lm .

Источник

Оцените статью
Adblock
detector