0

I have a program which use libevent library

when compile the program, the compiling command is like:

 gcc -o myprogram mysource.c mysource.h -levent 

so it is dynamic linking.

now I want to run this program on a computer where there is no libevent, I need static linking so that my program can be run on that computer, are there any easy steps?

I tried -static, but I got the following error:

    [root@kitty relay]# gcc  -o relay -static mysource.c mysource.h -levent -lpcap
    /usr/bin/ld: cannot find -lpcap
    /usr/bin/ld: cannot find -lc
    collect2: ld returned 1 exit status

why?

misteryes
  • 2,167
  • 4
  • 32
  • 58

2 Answers2

1

From the GCC documentation:

-static

On systems that support dynamic linking, this prevents linking with the shared libraries. On other systems, this option has no effect.

Community
  • 1
  • 1
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

You should have libevent.a. Then you can just gcc -o myprogram mysource.c libevent.a.

Or try gcc -o myprogram -static mysource.c -levent.

(And you probably shouldn't specify mysource.h to gcc as it's most likely included into mysource.c with #include "mysource.h".)

nullptr
  • 11,008
  • 1
  • 23
  • 18
  • if I have multiple shared library, like -lpcap, -levent, and I only want to statically link libevent but dynamically link libpcap, is it possible or not? thanks! – misteryes Jun 14 '13 at 15:43
  • Then do not specify `-static` option, but pass `libevent.a` to the linker (like in the first command) and add `-lpcap`. – nullptr Jun 14 '13 at 16:08
  • I tried `gcc -o relay -static mysource.c mysource.h /usr/local/lib/libevent.a -lpcap`, but I got errors: like `/home/wgong/Downloads/package/libevent-1.4.14b-stable/event.c:150: undefined reference to clock_gettime`. why? – misteryes Jun 14 '13 at 16:13
  • thanks, it is ok with `-lrt`, can you explain a bit about `-lrt`? thanks! – misteryes Jun 14 '13 at 16:37
  • It tells linker to use `librt` library. Well, I guess that libevent.so dynamically links againts librt.so (its functions use functions from librt), and it's handled by loader when we link libevent dynamically. But when we link libevent statically we need to resolve all calls from libevent at the link time. – nullptr Jun 14 '13 at 16:52