Home > Net >  How to check whether `malloc.h` is available in C?
How to check whether `malloc.h` is available in C?

Time:10-14

malloc.h is a non-standard C header that declares extensions to the C standard library related to memory management. It is available on Linux.

I want my program to compile on many platforms but only use malloc.h functionality when it is available.

How can I check during compile time (via macros) whether the malloc.h library is available for my C program?

Edit: a solution could also go indirectly, such as checking the operating system, or anything else.

CodePudding user response:

via macros

It's not possible to check for header existence "via macros".

Typically, create a small valid program with #include <malloc.h> and try to compile that program. If the compilation is successful, means the header is available. Build systems are tools created exactly for that goal of automating such tasks, there are for example: CHECK_INCLUDE_FILE() in cmake, AC_CHECK_HEADER() in autoconf, conf.CheckCHeader in scons, cc.has_header in meson, etc.

Note: there is a gcc extension __has_include https://gcc.gnu.org/onlinedocs/cpp/_005f_005fhas_005finclude.html that is going into C23 https://en.cppreference.com/w/c/23 . If you aim only for gcc or only for C23, you can use #if __has_include(<malloc.h>).

CodePudding user response:

You generate (autoconf, small c program, shell script etc) an header,s say, config.h, that only includes the header if is available. Optionally define a constant if you don't want to rely on what malloc.h defines:

#include <malloc.h>
#define MALLOC_H_FOUND 1

Then you code you include this header file and only perform actions based on a symbol found in malloc.h or the constant you defined above:

#include "config.h"

#ifdef _MALLOC_H // or MALLOC_H_FOUND
  // use malloc.c specific features
#else
 // fallback
#endif

CodePudding user response:

The easiest way to do this would be to try to compile a program that includes malloc.h, and then check the return code from the compiler. If the compiler returns an error, then malloc.h is not available.

Here's a simple example:

#include <stdio.h>
#include <malloc.h>

int main() {
  printf("Hello, world!\n");
  return 0;
}

If you try to compile this program on a system that doesn't have malloc.h, you'll get an error like this:

gcc test.c test.c:2:18: fatal error: malloc.h: No such file or directory #include <malloc.h> ^ compilation terminated.

If malloc.h is available, the program will compile without errors

  • Related