Help with programming in C

Status
Not open for further replies.

mizzycub

Est. Contributor
Messages
1,615
Role
  1. Adult Baby
  2. Diaper Lover
  3. Babyfur
Hi guys. I've recently started learning C. I have borrowed a good book from the library, and, as an exercise, I had to make a program to show the relative mass of an object at speeds close to c, for a rest mass of 1 kg. This is my program:

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

#define START 0.9*3e8
#define END 0.99*3e8
#define INC 0.01*3e8

double convert(double v)
{
	double m, m0, c;
	m0 = 1.0;
	c = 3.0e8;

	m = m0 / sqrt(1 - (v / c) * (v / c));
	return m;
}

int main(void)
{
	double v;
	double mass;
	
	for (v = START; v <= END; v += INC)
	{
		mass = convert(v);
		printf("At velocity %f%% of c, an object of rest mass 1 kg weighs %f kg", v, mass);
	}
	return 0;
}

However, when trying to compile I get this error.

Code:
[email protected]:~/Documents/C$ gcc relmass.c -o relmass
/tmp/cc4LgTLT.o: In function `convert':
relmass.c:(.text+0x50): undefined reference to `sqrt'
collect2: ld returned 1 exit status

As far as I understanding it it is saying that sqrt() is undefined. However I know that sqrt() is defined in math.h which I did include. So can anyone tell me what is going wrong.

If it helps I am running ubuntu 9.04 with gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4).

Can anyone tell me why this program won't compile, or spot any mistakes?

Thanks for your help.
 

element

Est. Contributor
Messages
119
Role
  1. Diaper Lover
You need to link the math shared library in when you compile. Try:
Code:
gcc relmass.c -lm -o relmass
The -lm flag tells GCC to link in the libm math library which has the sqrt (and other assorted math functions defined in math.h) function defined in it.
 

mizzycub

Est. Contributor
Messages
1,615
Role
  1. Adult Baby
  2. Diaper Lover
  3. Babyfur
Thanks for that. Solved it.

Note to self - find time to read through man gcc
 
Status
Not open for further replies.
Top