LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   gcc -linking (http://www.linuxquestions.org/questions/linux-newbie-8/gcc-linking-932087/)

brmchess 03-01-2012 01:00 AM

gcc -linking
 
I can create a linux executable with libs linked in with gcc-static,is
told to me. That simple is it. Where can I find tutorials on how to do
this - getting away with one compiler switch looks like fun.
Brian

Dark_Helmet 03-01-2012 01:33 AM

To compile with static libraries you need two things:
1. You need to have the static library itself installed. In linux, dynamic libraries usually end with a ".so" extension, and static libraries usually end in a ".a" extension. For example:
Code:

/usr/lib/libm.so
/usr/lib/libm.a

Also, if you look, the ".so" libraries are usually symbolic links to a more specific version library version. For instance, my /usr/lib/libm.so is a symbolic link to /usr/lib/libm.so.6.

2. You need to add "-static" to your link command. Assume you have a file named "main.c" that uses the math library (libm). You could compile and statically link the file in one step:
Code:

gcc -static -o myprogram main.c -lm
At that point, "myprogram" will by statically linked against your libm. It will not need to dynamically load anything from the libm library. You can confirm this by running:
Code:

ldd myprogram
If everything was linked statically, you should see a message similar to:
Code:

        not a dynamic executable

If you want something to test:
Code:

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

int main( int argc, char *argv[] )
{
  float base;
  float exponent;
  double baseToExponent;

  if( argc < 3 )
    return 1;

  base = strtof( argv[1], NULL );
  exponent = strtof( argv[2], NULL );

  baseToExponent = pow( base, exponent );
  printf( "%.2f^%.2f = %.2f\n", base, exponent, baseToExponent );

  return 0;
}

Save the above as main.c, and issue the command I gave earlier:
Code:

gcc -static -o myprogram main.c -lm
NOTE: when dealing with static linking, gcc is a little picky on the ordering. The libraries used (e.g. '-lm') need to come after the list of your source code files. Otherwise, you may get an "undefined reference" error.

knudfl 03-01-2012 02:34 AM

*

Mandriva : The static libc.a, libm.a etc. are provided
by the package glibc-static-devel.

brmchess 03-02-2012 01:30 AM

Dark_Helmet-thanks a lot for your trouble and quick reply.I am familiar with linux as
operator but not so much as programmer. Brian


All times are GMT -5. The time now is 01:38 AM.