Undefined reference to sqrt collect2 error ld returned 1 exit status

Undefined Reference to sqrt in C Problem:- Undefined reference to sqrt() in C Programming (or other mathematical functions) even includes math.h header Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt . This is a linker error. In the below program, We used sqrt() function […]

Содержание

  1. Undefined Reference to sqrt in C
  2. Solution
  3. unixforum.org
  4. Решено: sqrt из math.h и структуры (undefined reference to `sqrt’)
  5. Решено: sqrt из math.h и структуры
  6. Re: Решено: sqrt из math.h и структуры
  7. Re: Решено: sqrt из math.h и структуры
  8. Re: Решено: sqrt из math.h и структуры
  9. Re: Решено: sqrt из math.h и структуры
  10. Re: Решено: sqrt из math.h и структуры
  11. Re: Решено: sqrt из math.h и структуры
  12. Re: Решено: sqrt из math.h и структуры
  13. Re: Решено: sqrt из math.h и структуры
  14. Re: Решено: sqrt из math.h и структуры
  15. Re: Решено: sqrt из math.h и структуры
  16. Re: Решено: sqrt из math.h и структуры
  17. Re: Решено: sqrt из math.h и структуры
  18. Re: Решено: sqrt из math.h и структуры
  19. Русские Блоги
  20. GCC компилирует Math.h, решение для неопределенной ссылки
  21. Запись: GCC Compile Math.h
  22. 2. Решение
  23. 3. Причины
  24. Cygwin compilation error — collect2: error: ld returned 1 exit status #212
  25. Comments
  26. Footer
  27. С++. Что означает ошибка: [Error] ld returned 1 exit status.

Undefined Reference to sqrt in C

Problem:- Undefined reference to sqrt() in C Programming (or other mathematical functions) even includes math.h header

Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt . This is a linker error.

In the below program, We used sqrt() function and include math.h

If you are using a Linux environment, and when you compile the above program with,

Then you will get an error like this:-
/tmp/ccstly0l.o: In function main’:
test.c:(.text+0xb5): undefined reference tosqrt’
collect2: error: ld returned 1 exit status

Solution

This is a likely a linker error. The math library must be linked in when building the executable. So the only other reason we can see is a missing linking information. How to do this varies by environment, but in Linux/Unix, just add -lm to the command. We must link your code with the -lm option. If we are simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some information about your building process. To get rid of the problem undefined reference to sqrt in C, use below command to compile the program in place of the previous command.

The math library is named libm.so , and the -l command option assumes a lib prefix and .a or .so suffix. gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm . To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm .

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

unixforum.org

Форум для пользователей UNIX-подобных систем

  • Темы без ответов
  • Активные темы
  • Поиск
  • Статус форума

Решено: sqrt из math.h и структуры (undefined reference to `sqrt’)

Решено: sqrt из math.h и структуры

где я ошибся?

Re: Решено: sqrt из math.h и структуры

Сообщение fulltick » 17.10.2008 01:22

Re: Решено: sqrt из math.h и структуры

Re: Решено: sqrt из math.h и структуры

Сообщение e7reactor » 17.12.2010 16:38

Re: Решено: sqrt из math.h и структуры

Re: Решено: sqrt из math.h и структуры

Сообщение e7reactor » 17.12.2010 17:00

Re: Решено: sqrt из math.h и структуры

Re: Решено: sqrt из math.h и структуры

Сообщение e7reactor » 18.12.2010 09:10

Как пожелаете:
Spoiler

Re: Решено: sqrt из math.h и структуры

Сообщение agentprog » 18.12.2010 10:38

и да, main() по хорошему int возвращает, хоть это и не критично в данном случае.

Re: Решено: sqrt из math.h и структуры

Re: Решено: sqrt из math.h и структуры

Сообщение e7reactor » 18.12.2010 21:15

Re: Решено: sqrt из math.h и структуры

Сообщение hippi90 » 19.12.2010 00:12

Re: Решено: sqrt из math.h и структуры

Сообщение Илуватар » 19.12.2010 06:49

e7reactor, смотрите по теме:

1) Компилите с -lm и с Sqrt вместо sqrt
2) Указывают на ошибку с S-s
3) Компилите с sqrt но _без_ -lm — в результате получаете ошибку автора темы
4) Агент подсказывает нужное направление наводящим вопросом в своём посте, однако вы его не видите.

Сделайте всё правильно и выложите результат — не мучьте себя и комьюнити и дайте себя спасти (:

Re: Решено: sqrt из math.h и структуры

Сообщение e7reactor » 19.12.2010 11:20

e7reactor, смотрите по теме:

1) Компилите с -lm и с Sqrt вместо sqrt
2) Указывают на ошибку с S-s
3) Компилите с sqrt но _без_ -lm — в результате получаете ошибку автора темы
4) Агент подсказывает нужное направление наводящим вопросом в своём посте, однако вы его не видите.

Сделайте всё правильно и выложите результат — не мучьте себя и комьюнити и дайте себя спасти (:

Вот сейчас откомпилю с sqrt с маленькой буковки, и с -lm, и покажу результат
Может быть я уже пал настолько что спасти меня невозможно )

Источник

Русские Блоги

GCC компилирует Math.h, решение для неопределенной ссылки

Запись: GCC Compile Math.h

Скомпилируйте языковой файл C, содержащий функцию SQRT. Следующий код является примером.

Инструкции по компиляции следующие:

Все еще появляется:

Поиск крупных форумов скажет вам: я хочу добавить -lm , Библиотека ссылок ibm.so . но я сделал это.
Но если вы используете это напрямую:

Компиляция не будет иметь никаких проблем.

2. Решение

Используйте G ++ вместо GCC! Если это компиляция, измените CC на CXX:

3. Причины

Вот два способа объяснить различия между SQRT (4) и SQRT (A), но почему G ++ может решить эту проблему, и у GCC будет эта проблема без исследования. Что касается коренной причины, я надеюсь, что руководство большого парня.
Вот возможная причина,При использовании G ++ для компиляции файлов G ++ автоматически свяжет стандартную библиотеку STL, в то время как GCC не будет автоматически связывать STL
1. Прежде всего, первый — этот блог:GCC компилирует странное явление, содержащее программы Math.h (не беспрецедентные -lm)。
2. Используйте отладку GDB, чтобы обнаружить, что когда называются эти две функции, вызывается та же самая основная функция.

(1)、 sqrt(64): Вы можете видеть, что когда функция SQRT выполняется, основная функция не вызывается. Вы также можете знать код сборки, отображаемый в блоге выше.

(2)、 sqrt(a): Позвонить один w_sqrt_compat.c середина __sqrt Функция, затем снова позвоните e_sqrt.c середина __ieee754_sqrt функция

Источник

Cygwin compilation error — collect2: error: ld returned 1 exit status #212

Hello,
I want to compile SDK under Windows 8.1 using Cygwin

I use make STANDALONE=n and I still get collect2: error: ld returned 1 exit status error
Last lines from build.log

List of packages:

Any ideas how to fix this?

The text was updated successfully, but these errors were encountered:

This looks similar, mayby it helps? crosstool-ng/crosstool-ng#321

OK, this was a good tip. I found also other issues (I will request pull when I get SDK running on Cygwin), but now I cannot compile lx106-hal.

This can be connected with my 2 errors during xtensa-lx106-elf compilation? Because I got:

I had same issues.

For the first one, add —disable-tui to the gdb flags
For the second one, either use the patch I have supplied or, even better, switch to gcc5.2.0 and the problem will go away.

@davydnorris as I write before — I succesfully compile cross-gdb (also by adding -disable-tui). Now I’d like to compile libhal using your workaround, but alter ‘make clean’ file gcc/config.host is deleted, so I don’t know how to recompile all SDK.

So you have two options:

  • use my patch by saving it to a file in local-patches/gcc/4.8.5 where it will be automatically applied
  • use ct-ng menuconfig and change gcc to 5.2.0

I started with the first one but then changed to gcc5.2.0 (actually 5.4.0 now)

@davydnorris thanks! Now whole project compile without problems. I use GCC 4.8.5 with your patch, maybe in future crosstool-NG will switch to 5.4.0 version.
I added pull request with my findings to esp-open-sdk and crosstool-NG. I also pull request your patch for crosstool-NG (of course with information about author) — I hope that you don’t mind :).

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

С++. Что означает ошибка: [Error] ld returned 1 exit status.

Пожалуйста, скажите, в чем дело. Я новичок в программировании, чтение форумов с советами посмотреть лог сборки ничего не дало. Ниже сообщение компилятора об ошибке в полном размере и текст программы. Вместо функций прототипы, т. к. объем сообщения не позволяет вместить. (Кстати, с закомментированными функциями выдает ту же ошибку.) Пожалуйста, объясните доступно, если не тяжело.

Сообщение:
C:UsersTATIANAAppDataLocalTempccKtnbxh.oe4.cpp:(.text+0x811): undefined reference to `doubledec(char*)’
C:UsersTATIANAAppDataLocalTempccKtnbxh.oe4.cpp:(.text+0x81f): undefined reference to `binary(char*)’
C:UsersTATIANAAppDataLocalTempccKtnbxh.oe4.cpp:(.text+0x83b): undefined reference to `intdec(char*)’
C:UsersTATIANAAppDataLocalTempccKtnbxh.oe4.cpp:(.text+0x849): undefined reference to `hexadec(char*)’
C:UsersTATIANADesktopПрогиcollect2.exe[Error] ld returned 1 exit status

Текст программы:
#include
#include
#include //isdigit(), isxdigit()
#include //atoi()
#include //для функции gets()
using namespace std;

int empty_str (char *s); //ПРОВЕРЯЕТ, ПУСТА СТРОКА ИЛИ НЕТ.
void format_cmd (char *s); //КОРРЕКТИРУЕТ ФОРМАТ КОМАНДЫ ДЛЯ СРАВНЕНИЯ С ЗНАЧЕНИЯМИ ИЗ ПЕРЕЧИСЛЕНИЯ.
void doubledec (char *s); //РАБОТА С ВЕЩЕСТВЕННЫМИ ЧИСЛАМИ. ПРОВЕРЯЕТ, ЧТО ЭТО DOUBLE.
void intdec (char *s); //РАБОТА С ДЕСЯТИЧНЫМИ ЧИСЛАМИ. ПРОВЕРЯЕТ, ЧТО ЭТО ДЕС. ЧИСЛО.
void binary (char *s); //РАБОТА С ДВОИЧНЫМИ ЧИСЛАМИ. ПРОВЕРЯЕТ, ЧТО ЭТО ДВ. ЧИСЛО.
void octal (char *s);
void hexadec (char *s);//РАБОТА С ЦЕЛЫМИ ШЕСТНАДЦАТЕРИЧНЫМИ ЧИСЛАМИ. ПРОВЕРЯЕТ, ЧИСЛО ЛИ ЭТО.
int is_state_change (char *s); //ПРОВЕРЯЕТ, ЕСТЬ ЛИ КОМАНДА СМЕНЫ СОСТОЯНИЯ.

class calculator <
public:
calculator (); //конструктор
double current_value;//Текущее значение

int main()<
num_sys state = dbl;
calculator calc;
char str [100];

while (1) <
cout Лучший ответ

Источник

Ezoic

Problem:- Undefined reference to sqrt() in C Programming (or other mathematical functions) even includes math.h header

Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt. This is a linker error.

In the below program, We used sqrt() function and include math.h

#include<stdio.h>
#include<math.h>
int main()
{
   int x = 9, result;
   result = sqrt(x);
   printf("Square root = %dn", result);
   return 0;
}

If you are using a Linux environment, and when you compile the above program with,

gcc test.c -o test

Then you will get an error like this:-
/tmp/ccstly0l.o: In function main':
test.c:(.text+0xb5): undefined reference tosqrt'
collect2: error: ld returned 1 exit status

Solution

This is a likely a linker error. The math library must be linked in when building the executable. So the only other reason we can see is a missing linking information. How to do this varies by environment, but in Linux/Unix, just add -lm to the command. We must link your code with the -lm option. If we are simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some information about your building process. To get rid of the problem undefined reference to sqrt in C, use below command to compile the program in place of the previous command.

gcc test.c -o test -lm
Undefined reference to sqrt in C

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix. gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

More C programming examples

  • C Program Without Main() Function
  • Print hello world without using semicolon
  • Get the Process ID & parent Process ID
  • fork() in C
  • Why gets function is dangerous and should not be used
  • Undefined reference to sqrt (or other mathematical functions) even includes math.h header
  • Find the length of String
  • Copy two Strings
  • Concatenate Two Strings
  • Compare two strings
  • Reverse a String
  • Find string is a palindrome or not
  • Search position of Nth times occurred element in array
  • Remove all characters in a string except alphabet
  • Find the frequency of characters in a string
  • C program to count the number of words in a string
  • C program to count lines words and characters in a given text
  • Vowel consonant digit space special character Count in C Programming
  • String pattern in C language
  • Uppercase character into the lowercase character
  • Lowercase character into the uppercase character
  • C program to search a string in the list of strings
  • Sort Elements in Lexicographical Order (Dictionary Order)

Ezoic

Решено: sqrt из math.h и структуры (undefined reference to `sqrt’)

Модератор: Модераторы разделов

Аватара пользователя

—=Civil696=—

Сообщения: 227
ОС: Gentoo o_O

Решено: sqrt из math.h и структуры

пишу вот такой код: # на самом деле это не всё, но остальное компилится и работает…

Код: Выделить всё

#include <math.h>
struct vect {
    double x;
    double y;
    };

double vectdlina(struct vect a)
{
    return sqrt(a.x * a.x + a.y * a.y);
}

на что компилятор отвечает мне:

Код: Выделить всё

navi C $ cc myvector.c
/tmp/cc4W8xkO.o: In function `vectdlina':
myvector.c:(.text+0x108): undefined reference to `sqrt'
collect2: выполнение ld завершилось с кодом возврата 1

самое интересное, что в K&R, в самом начале главы о структурах, есть аналогичный код:

Код: Выделить всё

struct point pt;
double dist, sqrt(double);

dist = sqrt((double)pt.x * pt.x + (double)pt.y * pt.y);

но вот это:

Код: Выделить всё

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

struct point {
    int x;
    int y;
};

int main () {
    double c, sqrt(double);
    struct point a = { 12 , 3 };

    c = sqrt((double) a.x * a.x + a.y * b.y);
    printf("%.f", c);

    return 0;
}

тоже не компилится

Код: Выделить всё

navi C $ cc point.c
/tmp/ccBEtljl.o: In function `main':
point.c:(.text+0x6e): undefined reference to `sqrt'
collect2: выполнение ld завершилось с кодом возврата 1

где я ошибся? :unsure:

НЕ ПАНИКУЙ © ^_~

Аватара пользователя

e7reactor

Сообщения: 16
ОС: Linux

Re: Решено: sqrt из math.h и структуры

Сообщение

e7reactor » 17.12.2010 16:38

—=Civil696=— писал(а): ↑

17.10.2008 01:28

fulltick писал(а): ↑

17.10.2008 01:22

$ cc myvector.c -lm

Хм… Надо будет, помимо чтения книжек по C, ман к gcc наконец почитать, хотябы по диагонали… >_<
Спасибо большое… :blush:
Тему можно закрывать :)

подождите, незакрывайте…
вот у меня такая же шляпа получается. Написал прогу, вней синусы, косинусы, корень квадратный
делаю

заметте -lm пишу!!!
а он пишет

Код: Выделить всё

fourier.c:(.text+0x56c): undefined reference to `Sqrt'

Подскажите как всё таки бороться с компилятором?
Спасибо заранее

Изображение
Linux OpenSuSE 11.0

Аватара пользователя

e7reactor

Сообщения: 16
ОС: Linux

Re: Решено: sqrt из math.h и структуры

Сообщение

e7reactor » 18.12.2010 09:10

shotdownsystem писал(а): ↑

17.12.2010 17:02

тогда текст программы
и ls -l |grep libm

Как пожелаете:

Spoiler

Код: Выделить всё

#include <stdio.h>
#include <math.h>
void main( void );
float geta ( double );
float getb ( double );
float getsee ( void );
float g( double );
double width = 0.0001;
double rightorleft=0;
int numterms=10;
double T=1;
double f=1;
void main( void) {
    double a[ numterms + 1], b[ numterms + 1], c, ctoo, n;
    int i, j;
    printf( "n" );
    c = getsee( );
    for ( n=1; n <= numterms; n++ ) {
        i = n;
        a[ i ] = geta( n );
    }
    for ( n=1; n <= numterms; n++ ) {
        i = n;
        b[ i ] = getb( n );
    }
    rightorleft = width;
    ctoo = getsee();
    for ( i = 1; i <= numterms; i++ ) {
        printf( "%s%d%s", "a", i, " is: " );
        printf( "%lf", a[ i ]);
        printf( "%s%d%s", "                  b", i , " is: ");
        printf( "%lfn", b[ i ]);
    }
    printf( "n%s%lfn", "c is ", c );
    printf( "%s%lfnn", "ctoo is ", ctoo );

}

float geta( double n ) {
    double i;
    float total = 0;
    double end;
    if (rightorleft==0) end = T - width;
    else end = T;

    for ( i = rightorleft; i <= end; i+=width)
        total += width * ( g( i ) * cos(6.28 * n * f * i ) );
    total *= 2/T;
    return total;
}

float getb( double n ) {
    double i;
    float total = 0;
    double end;

    if (rightorleft == 0 ) end = T - width;
    else end = T;

    for ( i = rightorleft; i<= end; i+=width)
        total += width * ( g( i ) * sin(6.28 * n * f * i ) );
    total *= 2/T;
    return total;
}


float getsee(void) {
    double i;
    float total = 0;
    double end;

    if (rightorleft == 0 ) end = T - width;
    else end = T;

    for ( i = rightorleft; i <= end; i+= width )
        total += width * g( i );
    total *= 2/T;
    return total;
}

float g( double t ) {
    return sqrt(1/( 1 + t ));
}

попытка компиляции:

Код: Выделить всё

> gcc fourier1.c
fourier1.c: In function ‘main’:
fourier1.c:13: warning: return type of ‘main’ is not ‘int’
/tmp/ccl5MK1w.o: In function `geta':
fourier1.c:(.text+0x39c): undefined reference to `cos'
/tmp/ccl5MK1w.o: In function `getb':
fourier1.c:(.text+0x471): undefined reference to `sin'
/tmp/ccl5MK1w.o: In function `g':
fourier1.c:(.text+0x5a2): undefined reference to `sqrt'
collect2: ld returned 1 exit status
>

ls -l:

Код: Выделить всё

-rw-r--r-- 1 name user     1777 Дек 18 12:03 fourier1.c

ecли ls -l | grep libm, то выдаёт пустую строку.

Изображение
Linux OpenSuSE 11.0

Аватара пользователя

agentprog

Сообщения: 362
Статус: Ad Astra per aspera
ОС: openSUSE 11.4, Arch

Re: Решено: sqrt из math.h и структуры

Сообщение

agentprog » 18.12.2010 10:38

e7reactor писал(а): ↑

17.12.2010 16:38

заметте -lm пишу!!!

e7reactor писал(а): ↑

18.12.2010 09:10

> gcc fourier1.c

где?

Код: Выделить всё

agent@notebook:~> gcc -o tm tm.c -lm
agent@notebook:~> ./tm

a1 is: 0.014061                  b1 is: 0.089179
a2 is: 0.003285                  b2 is: 0.046068
a3 is: 0.001108                  b3 is: 0.030927
a4 is: 0.000328                  b4 is: 0.023255
a5 is: -0.000036                  b5 is: 0.018628
a6 is: -0.000234                  b6 is: 0.015536
a7 is: -0.000354                  b7 is: 0.013325
a8 is: -0.000432                  b8 is: 0.011664
a9 is: -0.000486                  b9 is: 0.010373
a10 is: -0.000524                  b10 is: 0.009339

c is 1.656883
ctoo is 1.656825

agent@notebook:~>

и да, main() по хорошему int возвращает, хоть это и не критично в данном случае.

No problems — just solutions!

Аватара пользователя

e7reactor

Сообщения: 16
ОС: Linux

Re: Решено: sqrt из math.h и структуры

Сообщение

e7reactor » 18.12.2010 21:15

shotdownsystem писал(а): ↑

18.12.2010 12:19

имелось ввиду
ls -l /lib | grep libm
если еще актуально

Код: Выделить всё

~> ls -l /lib | grep libm
-rwxr-xr-x  1 root root  171996 Дек 17  2008 libm-2.8.so
-rwxr-xr-x  1 root root   14324 Дек 17  2008 libmemusage.so
lrwxrwxrwx  1 root root      11 Дек 25  2009 libm.so.6 -> libm-2.8.so

agentprog писал(а): ↑

18.12.2010 10:38

где?

Не знаю. У Вас видимо всё нормально. а у меня хрень какая-то с gcc

Изображение
Linux OpenSuSE 11.0

Аватара пользователя

Илуватар

Сообщения: 295
Статус: Antic1tizen 0ne
ОС: Debian Wheezy/Sid amd64
Контактная информация:

Re: Решено: sqrt из math.h и структуры

Сообщение

Илуватар » 19.12.2010 06:49

e7reactor, смотрите по теме:

1) Компилите с -lm и с Sqrt вместо sqrt
2) Указывают на ошибку с S-s
3) Компилите с sqrt но _без_ -lm — в результате получаете ошибку автора темы
4) Агент подсказывает нужное направление наводящим вопросом в своём посте, однако вы его не видите.

Сделайте всё правильно и выложите результат — не мучьте себя и комьюнити и дайте себя спасти (:

† Obiit animus, natus est atomus †

Аватара пользователя

e7reactor

Сообщения: 16
ОС: Linux

Re: Решено: sqrt из math.h и структуры

Сообщение

e7reactor » 19.12.2010 11:20

Илуватар писал(а): ↑

19.12.2010 06:49

e7reactor, смотрите по теме:

1) Компилите с -lm и с Sqrt вместо sqrt
2) Указывают на ошибку с S-s
3) Компилите с sqrt но _без_ -lm — в результате получаете ошибку автора темы
4) Агент подсказывает нужное направление наводящим вопросом в своём посте, однако вы его не видите.

Сделайте всё правильно и выложите результат — не мучьте себя и комьюнити и дайте себя спасти (:

Вот сейчас откомпилю с sqrt с маленькой буковки, и с -lm, и покажу результат
Может быть я уже пал настолько что спасти меня невозможно :))

О чудо! Получилось!

Код: Выделить всё

>gcc fourier1.c -lm -o four
fourier1.c: In function ‘main’:
fourier1.c:13: warning: return type of ‘main’ is not ‘int’
> ./four

a1 is: 0.014061                  b1 is: 0.089179
a2 is: 0.003285                  b2 is: 0.046068
a3 is: 0.001108                  b3 is: 0.030927
a4 is: 0.000328                  b4 is: 0.023255
a5 is: -0.000036                  b5 is: 0.018628
a6 is: -0.000234                  b6 is: 0.015536
a7 is: -0.000354                  b7 is: 0.013325
a8 is: -0.000432                  b8 is: 0.011664
a9 is: -0.000486                  b9 is: 0.010373
a10 is: -0.000524                  b10 is: 0.009339

c is 1.656883
ctoo is 1.656825

>

Спасибо, Небеса!!!

Изображение
Linux OpenSuSE 11.0

Iwanna

0 / 0 / 0

Регистрация: 01.12.2014

Сообщений: 27

1

24.12.2014, 22:32. Показов 7897. Ответов 5

Метки нет (Все метки)


C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
int fd[2];
size_t size;
int side[2];
side[0]=4; /*сторона1 */
side[1]=3; /*сторона2 */
side[2]=3; /*сторона3 */
int reside[2];
if(pipe(fd) < 0){
/* Если создать pipe не удалось, печатаем об этом сообщение
и прекращаем работу */
printf("Can't create pipen");
exit(-1);
}
size = write(fd[1], side, sizeof(side));
if(size != sizeof(side)){
printf("Can't write all stringn");
exit(-1);
}
/* Пробуем прочитать из pip'а 14 байт в другой массив, т.е. всю
записанную строку */
size = read(fd[0], reside, sizeof(side));
if(size < 0){
/* Если прочитать не смогли, сообщаем об ошибке */
printf("Can't read stringn");
exit(-1);
}
int plo;
int p = ((reside[0] + reside[1] + reside[2])/2);;
    plo = sqrt(p*(p - reside[0]) * (p - reside[1]) * (p - reside[2]));
/* Печатаем прочитанную строку */
printf("%dn",plo);
/* Закрываем входной поток*/
if(close(fd[0]) < 0){
printf("Can't close input streamn");
}
/* Закрываем выходной поток*/
if(close(fd[1]) < 0){
printf("Can't close output streamn");
}
return 0;
}

Собственно:

C
1
2
3
4
5
6
7
1.c: In function ‘main’:
1.c:36:11: warning: incompatible implicit declaration of built-in functionsqrt[enabled by default]
     plo = sqrt(p*(p - reside[0]) * (p - reside[1]) * (p - reside[2]));
           ^
/tmp/ccsmSQxx.o: In function `main':
1.c:(.text+0xd6): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Псевдослучайный

1946 / 1145 / 98

Регистрация: 13.09.2011

Сообщений: 3,215

24.12.2014, 22:35

2

Лучший ответ Сообщение было отмечено Iwanna как решение

Решение

#include <math.h>
При сборке добавить в опции -lm



1



Iwanna

0 / 0 / 0

Регистрация: 01.12.2014

Сообщений: 27

24.12.2014, 22:56

 [ТС]

3

После добавления math

C
1
2
3
/tmp/ccJuL9Lq.o: In function `main':
1.c:(.text+0xd6): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

Добавлено через 15 минут
Для компиляции использую команду gcc -o 1 1.c



0



528 / 430 / 159

Регистрация: 25.11.2014

Сообщений: 1,662

24.12.2014, 23:12

4

Цитата
Сообщение от Iwanna
Посмотреть сообщение

Для компиляции использую команду gcc -o 1 1.c

gcc -o 1 1.c -lm



1



0 / 0 / 0

Регистрация: 01.12.2014

Сообщений: 27

24.12.2014, 23:23

 [ТС]

5

Да- да, не подскажите что делает опция -lm?



0



528 / 430 / 159

Регистрация: 25.11.2014

Сообщений: 1,662

25.12.2014, 10:35

6

Цитата
Сообщение от Iwanna
Посмотреть сообщение

Да- да, не подскажите что делает опция -lm?

Она говорит компоновщику, с какими библиотеками компоновать программу. Это была ошибка не компилятора. Загугли, почитай про компоновку (линковку), станет понятнее.



1



Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

So, I bought a copy of Modern C by Jens Gustedt (Manning 2019) (publisher’s link). Brush up my C, I thought. Get it for $19.99 at a full 50% discount rather than paying $20  I am liking the book, but hit a problem when I found the exercise about the use of the

?:

operator to allow negative square roots. If you have a copy with page numbers, it’s on page 45, otherwise §4.4. This is what Gustedt writes:-I thought, that looks interesting; I must try it out, bit I am getting this sort of compiler error:-

gcc -o root_error root_error.c

/usr/bin/ld: /usr/lib/gcc/x86_64-redhat-linux/9/../../../../lib64/crt1.o: in function `_start’:

(.text+0x24): undefined reference to `main’

/usr/bin/ld: /tmp/ccVjsV0O.o: in function `sqrt_real’:

root_error.c:(.text+0x2a): undefined reference to `sqrt’

/usr/bin/ld: root_error.c:(.text+0x48): undefined reference to `sqrt’

collect2: error: ld returned 1 exit status

I could write a function prototype and

main()

and add

#include <math.h>

, but nothing seems to make that error about sqrt go away. What am I doing wrong? I am getting the same error on my Fedora31 laptop and our UbuntuMate 19.10 box at home

Saloon Keeper

Posts: 14713


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Can you try compiling with

-std=c11

?


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

…and link with the math library ie. add -lm on the end of your gcc command line.

Regarding the main error, you’re getting that because the compiler thinks you’re compiling an executable, which must have a main() function which the OS calls when you run the executable. If you aren’t creating an executable, add -c to the compiler command line.

John Matthews

Rancher

Posts: 473


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

me wrote:If you aren’t creating an executable, add -c to the compiler command line.

So:

works for me, creating object file moose.o.

John Matthews

Rancher

Posts: 473


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

John Matthews wrote:Regarding the main error…

Sorry Campbell — only just spotted who posted the question. I’m guessing you know this bit

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Thank you so much, and sorry for taking so long to reply. The

-std=c11

(I also tried

-std=c17

) and

-lm

options got rid of that particular error about sqrt. Unfortunately, when I tried to add

main()

, I started getting other errors. I shall try playing with code and searching before coming back to ask again.

Is

complex

a keyword? Gustedt suggested that the

tgmath.h

file would contain everything necessary to run that code.

John Matthews

Rancher

Posts: 473


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Is complex a keyword? Gustedt suggested that the tgmath.h file would contain everything necessary to run that code.

I’m only googling this myself, but it looks like tgmath.h #includes complex.h, which defines

complex

as a macro:

https://pubs.opengroup.org/onlinepubs/009695399/basedefs/complex.h.html

As complex.h is #included by tgmath.h then you shouldn’t have to.

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

The link you provided was very helpful; thank you. It also ways that

tgmath.h

should contain

sqrt(double)

too. It says something about ISO C in 2001. Don’t know whether that means it was introduced after C99, but that would seem unlikely.

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

So far, so good. It seems that

-lm

is the crucial tag; it enabled me to get a program to run and tell me √123.45E67.

Thank you. Shall try complex numbers soon.

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Thank you again:Working nicely;

root_real()

and

root_real2()

seem to do the same thing, so I can use one or the other in line 17. I don’t think they are really good function names, but I simply copied Gustedt’s names.

campbell@xxxxx$ gcc root.c -lm

campbell@xxxxx$ ./a.out 123.45e67

The root of |1.2345e+69| is 3.51355e+34

Complex version of root = (3.51355e+34, 0i)

campbell@xxxxx$ ./a.out -123.45e67

The root of |-1.2345e+69| is 3.51355e+34

Negative number: Complex version of root = (0, 3.51355e+34i)

Stephan van Hulst

Saloon Keeper

Posts: 14713


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Why do you have forward declarations when you can just move the main function to the bottom?

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I never knew you could do that. So I can get rid of the prototypes and move

main()

to the end? No sooner said that done.

If you have multiple functions in the same file, that does mean you have to declare them in a certain order, before they are used. If you declare prototypes for everything other than

main()

, you can have the functions in any order.

John Matthews

Rancher

Posts: 473


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

While we’re in code review mode…

I would suggest changing:

to more like ‘normal’ C(++):

and of course you’d add a check for argc>1 before releasing it into the wild.

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Thank you. I wasn’t planning to release that code, but since I have posted it here, it will have escaped like a ‘flu virus anyway.


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Campbell Ritchie wrote:I never knew you could do that. So I can get rid of the prototypes and move

main()

to the end? No sooner said that done.

If you have multiple functions in the same file, that does mean you have to declare them in a certain order, before they are used. If you declare prototypes for everything other than

main()

, you can have the functions in any order.

The C/C++ compiler parses from to bottom. A prototype is just a way of declaring the signature for a function without (yet) declaring its body so that other code can compile calls to that function correctly.

If you have defined the function before you call it then you don’t need a prototype at all. And, for that matter, in the dialect I use for Arduino code, you generally don’t need a prototype unless the method in question is declared static.

I like my main() method to be at the bottom anyway. So I can find it easily.

As to the main(int argc, char **argv) versus main(int argc, char *argv[]), they are ultimately the same definition, just different notation. You can declare char **argv and retrieve strtod(argv[1]) and that works just fine. I’m neutral on that one. I’ve done it both ways without spending much thought on it.

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.

John Matthews

Rancher

Posts: 473


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Tim Holloway wrote:As to the main(int argc, char **argv) versus main(int argc, char *argv[]), they are ultimately the same definition, just different notation.

Sure, it’s probably the least of Campbell’s problems But to me, *argv[] maps more closely to what the argument is, logically. That is, an array of strings, rather than just a pointer to a pointer. And argv[i] is how you normally access an array element.

Tim Holloway

Saloon Keeper

Posts: 26557

Android
Eclipse IDE
Tomcat Server
Redhat
Java
Linux


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

John Matthews wrote:And argv[i] is how you normally access an array element.

Well, until you’ve worked with C long enough that your brain cells begin to erode. Then you start coding stuff like (argv + 3).

Oh, and just to clarify on the sqrt undefined. The sqrt and trig and exponential functions are all (originally) implemented algorithmically, so you need to link in a math library in most implementations. Modern systems typically have an integral math processor do do much, if not all of that stuff in a single machine instruction, but way back when, I think they actually stole the Fortran math library in some implementations. Today, some systems allow multiple options, including native/versus library math (via a #pragma or compiler switch), and differing floating-point formats (IBM legacy mainframe FP is considerably different from IEEE form and if you want to faithfully re-create old NASA computations or something…)

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.

Campbell Ritchie

Marshal

Posts: 77299


posted 3 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Tim Holloway wrote:. . .  main(int argc, char **argv) versus main(int argc, char *argv[]), they are ultimately the same definition . . .

Yes, I knew that bit. But the other info you provided is very interesting (as it always is). Thank you.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Problem:- Undefined reference to sqrt() in C Programming (or other mathematical functions) even includes math.h header

Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt. This is a linker error.

you will get an error like this:-

/tmp/ccstly0l.o: In function main’:

test.c:(.text+0xb5): undefined reference tosqrt’

collect2: error: ld returned 1 exit status

This is a likely a linker error. The math library must be linked in when building the executable. So the only other reason we can see is a missing linking information. How to do this varies by environment, but in Linux/Unix, just add -lm to the command. We must link your code with the -lm option. If we are simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some information about your building process. To get rid of the problem undefined reference to sqrt in C, use below command to compile the program in place of the previous command.

For Solution visit:- Undefined Reference to sqrt in C Programming

Понравилась статья? Поделить с друзьями:
  • Undefined reference to pow collect2 error ld returned 1 exit status
  • Undefined reference to main collect2 error ld returned 1 exit status
  • Undefined reference to collect2 exe error ld returned 1 exit status
  • Undefined object 7 error index primary does not exist
  • Undefined function or variable matlab как исправить