Question

Its a long time since I've used C but now I'm trying to compile a short script that gets server-stats from the Apache-Portable-Runtime (APR).

Header files located at /usr/include/apr-1/apr*.h and libs are located at /usr/lib64/libapr-1.*

Source files can be found on the official APR site http://apr.apache.org/docs/apr/1.3/files.html.

/* test.c */
#include <stdio.h>
#include <stdlib.h>
#include <apr_general.h>
#include <apr_time.h>

int main(int argc, const char *argv[])
{
    apr_time_t t;
    t = apr_time_now();
    printf("The current time: %" APR_TIME_T_FMT "[us]\n", t);
    return 0;
}

When I try and compile I get the following error (which I believe is a linking issue):

~> gcc -Wall $(apr-1-config --cflags --cppflags --includes --link-ld) test.c -o test.bin
/tmp/cc4DYD2W.o: In function `main':
test.c:(.text+0x10): undefined reference to `apr_time_now'
collect2: ld returned 1 exit status

My environment is gentoo:

~> uname -a
Linux alister 2.6.32.21-grsec-gt-r2 #1 SMP Tue Sep 7 23:54:49 PDT 2010\
x86_64 Intel(R) Xeon(R) CPU L5640 @ 2.27GHz GenuineIntel GNU/Linux`
~> gcc -v 
gcc version 4.3.4 (Gentoo 4.3.4 p1.1, pie-10.1.5)
~> emerge --search "%@^dev-lib.*apr"
*  dev-libs/apr
   Latest version installed: 1.3.9
*  dev-libs/apr-util
   Latest version installed: 1.3.9

Does anyone with more experience with C on Linux have any suggestions for me to get this working?

As always thanks in advance.

Was it helpful?

Solution 2

I finally got around to looking into this.

gcc mentions -l twice in different contexts:

Linker Options
object-file-name -llibrary ...
Directory Options
... -Idir -Ldir ...

so I moved the -llib after the object name (to get the 2nd context) and it compiled!

APR_CFG=$(apr-1-config --cflags --cppflags --includes --link-ld) 
gcc -Wall test.c -o test.bin $APR_CFG
./test.bin
The current time: 1332999950442660[us]

I'm not fully sure I understand the linking order and why it didn't work before (if someone could shed some light on that it would be fantastic) but for now I have enough to continue.

OTHER TIPS

gcc -Wall -I/usr/include/apr-1 -L/usr/lib64 -lapr-1 test.c -o test.bin

-l specifies which shared library to link to, while -L specifies where to look for shared libraries.

APR provides a tool to make this easier, apr-1-config. Something like this should work:

gcc -Wall $(apr-1-config --cflags --cppflags --includes --link-ld) test.c -o test.bin
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top