x13n
x13n

Reputation: 4153

How to tell if glibc is used

I am trying to implement backtrace functionality for a large framework, which is used for different platforms and OS'es. In some of them, it is linked against glibc, while in the other, something different (eg. uclibc) is used. backtrace() function exists only in the former.

Is there any way to tell whether glibc is used? Any #define? I was unable to find an answer in glibc manual. I know I can't have linking-time information during compilation, but I guess include files have to differ. At least backtrace have to be declared somewhere. I would like to check it without being forced to pass explicit flags to the compiler.

Upvotes: 30

Views: 21734

Answers (5)

Gunther Piez
Gunther Piez

Reputation: 30419

There are the #defines __GNU_LIBRARY__, __GLIBC__ and __GLIBC_MINOR__ (6, 2 and 11 on my system with glibc-2.11) in features.h.

Upvotes: 30

Jagger Yu
Jagger Yu

Reputation: 637

#if defined(__GLIBC__) && !defined(__UCLIBC__) && !defined(__MUSL__)

This is getting a bit ugly and syntactically ambiguous, but useful.

Upvotes: 2

Empirically, both of the following compile and run fine on GCC 6.4:

#include <stdio.h>

int main(void) {
#ifdef __GLIBC__
    puts("__GLIBC__");
#endif
    return 0;
}

and:

int main(void) {
#ifdef __GLIBC__
    puts("__GLIBC__");
#endif
    return 0;
}

but only the first produces output of course.

This must mean that __GLIBC__ comes from stdio.h which must include features.h, see also: What is the purpose of features.h header?

Therefore, strictly speaking, __GLIBC__ by itself is not a clear indication that glibc is used, since even without headers, GCC already embeds runtime objects such as crt1.o in the finale executable, and those come from glibc.

So the main missing question is: does glibc guarantee that features.h gets included by every header? I could not find a clear documentation quote. TODO.

Upvotes: 2

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215183

Checking for preprocessor macros is not a good solution. uClibc and possibly other libc implementations define macros to mimic glibc (without providing all of its bloated functionality) for much the same reasons that all browsers include "Mozilla" in their User-Agent strings: broken programs that expect to see glibc and turn off lots of features if they don't see it.

Instead you should write a configure script to probe for backtrace and use it only if it's available.

Upvotes: 6

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36977

Include features.h, it contains the macros you need, e.g.

#define __GNU_LIBRARY__ 6

/* Major and minor version number of the GNU C library package.  Use
   these macros to test for features in specific releases.  */
#define __GLIBC__       2
#define __GLIBC_MINOR__ 4

Upvotes: 39

Related Questions