Неопределенная ссылка на sqrt collect2 error ld returned 1 exit status

I'm very new to C and I have this code: #include #include int main(void) { double x = 0.5; double result = sqrt(x); printf("The square root of %lf is %lfn", x,

I’m very new to C and I have this code:

#include <stdio.h>
#include <math.h>
int main(void)
{
  double x = 0.5;
  double result = sqrt(x);
  printf("The square root of %lf is %lfn", x, result);
  return 0;
}

But when I compile this with:

gcc test.c -o test

I get an error like this:

/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Why does this happen? Is sqrt() not in the math.h header file? I get the same error with cosh and other trigonometric functions. Why?

Wolf's user avatar

Wolf

9,4947 gold badges62 silver badges105 bronze badges

asked May 2, 2012 at 6:53

Ant's's user avatar

4

The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm to the command:

gcc test.c -o test -lm

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.

answered May 2, 2012 at 6:55

wallyk's user avatar

wallykwallyk

56.4k16 gold badges85 silver badges147 bronze badges

2

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

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.

answered May 2, 2012 at 6:55

Abhijit's user avatar

AbhijitAbhijit

61.1k18 gold badges130 silver badges201 bronze badges

This is a likely a linker error.
Add the -lm switch to specify that you want to link against the standard C math library (libm) which has the definition for those functions (the header just has the declaration for them — worth looking up the difference.)

answered May 2, 2012 at 6:55

ckhan's user avatar

ckhanckhan

4,67623 silver badges26 bronze badges

Because you didn’t tell the linker about location of math library. Compile with gcc test.c -o test -lm

answered May 2, 2012 at 6:56

tuxuday's user avatar

tuxudaytuxuday

2,96117 silver badges18 bronze badges

Add header:

#include<math.h>

Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.

abs()- provides absolute values;

example, abs(-3) =3

Include -lm at the end of your command during compilation time:

gcc <filename.extension> -lm

answered Mar 3, 2017 at 5:29

Akshat's user avatar

AkshatAkshat

711 silver badge7 bronze badges

I’m very new to C and I have this code:

#include <stdio.h>
#include <math.h>
int main(void)
{
  double x = 0.5;
  double result = sqrt(x);
  printf("The square root of %lf is %lfn", x, result);
  return 0;
}

But when I compile this with:

gcc test.c -o test

I get an error like this:

/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Why does this happen? Is sqrt() not in the math.h header file? I get the same error with cosh and other trigonometric functions. Why?

Wolf's user avatar

Wolf

9,4947 gold badges62 silver badges105 bronze badges

asked May 2, 2012 at 6:53

Ant's's user avatar

4

The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm to the command:

gcc test.c -o test -lm

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.

answered May 2, 2012 at 6:55

wallyk's user avatar

wallykwallyk

56.4k16 gold badges85 silver badges147 bronze badges

2

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

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.

answered May 2, 2012 at 6:55

Abhijit's user avatar

AbhijitAbhijit

61.1k18 gold badges130 silver badges201 bronze badges

This is a likely a linker error.
Add the -lm switch to specify that you want to link against the standard C math library (libm) which has the definition for those functions (the header just has the declaration for them — worth looking up the difference.)

answered May 2, 2012 at 6:55

ckhan's user avatar

ckhanckhan

4,67623 silver badges26 bronze badges

Because you didn’t tell the linker about location of math library. Compile with gcc test.c -o test -lm

answered May 2, 2012 at 6:56

tuxuday's user avatar

tuxudaytuxuday

2,96117 silver badges18 bronze badges

Add header:

#include<math.h>

Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.

abs()- provides absolute values;

example, abs(-3) =3

Include -lm at the end of your command during compilation time:

gcc <filename.extension> -lm

answered Mar 3, 2017 at 5:29

Akshat's user avatar

AkshatAkshat

711 silver badge7 bronze badges

Содержание

  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

Iwanna

0 / 0 / 0

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

Сообщений: 27

1

24.12.2014, 22:32. Показов 7904. Ответов 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



Решено: 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

Понравилась статья? Поделить с друзьями:
  • Неправильное имя пользователя или пароль ошибка при выполнении запроса post к ресурсу e1cib login
  • Неопределенная ссылка на main collect2 error ld returned 1 exit status
  • Неправильное имя пользователя или пароль windows 11 как исправить
  • Неопределенная сетевая ошибка 0x8009001 герои 6
  • Неоправданные повторы слов относятся к ошибкам