Problem linking the header files in GCC Linux .

Sometimee u will find that ur program in c or c++ is unable 2 link the header file resulting 2 (compilation) linking error . This limitation can be fixed by the following ::

gcc -o sample -lm sample.c

OR

cc -o sample -lm sample.c

Now u know the solution go ahead n codeee ..


Advertisement

2 Responses

  1. Actually the error is a linker error, and not a compilation error. When you include the header file of some library, the compiler knows that the functions declared in the header files will be used in the program, and so it compiles the code without the definition. Now when linking the function calls with the function definitions the linker cannot find the object code of the functions which you have called in the program, and so the linker shows the error message, and the function foo () is undefined.
    The example you have shown links the compiled code with the math library only. the -lm is expanded to libm.a (static linking), libm.so (dynamic linkin) and this file is searched in your lib directory in the system (/usr/lib). So if you use any math.h library functions and then compile the code, it will throw the linker error, and to link the math library that is the libm.so the -lm is added.
    Instead if you were using some other library, then you need to link it with the proper library. For example if you are using pthread.h and doing multi threaded programming, then you need to link it with the proper library with the -lpthread switch, and if you are doing coding with curses.h, then you need to so -lcurses, etc, .
    The library which you need to include when compiling is stated in the manual of that library. For example if you are using sqrt () function, then to see the manual of sqrt (), type in
    man sqrt
    in the terminal, and you will see that it says to link the code with -lm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.