2

I've heard of a lot of cool GCC extensions and built-in functions over the years, but I always wind up forgetting about them before thinking of using them.

What are some cool GCC extensions and built-ins, and some real-life examples of how to put them to use?

salezica
  • 74,081
  • 25
  • 105
  • 166
  • 4
    If you want to write portable code, you will stay away from (gcc) extensions. – pmg Jan 24 '12 at 15:50
  • Despite extensions being bad, some builtin functions (with the same names as standard ones) are very useful because they make operations that might seem slow/inefficient actually practical. – R.. GitHub STOP HELPING ICE Jan 24 '12 at 16:36
  • 1
    You may also find this question useful: http://stackoverflow.com/questions/3375697/useful-gcc-flags-for-c – Matt Joiner Jan 24 '12 at 16:40

3 Answers3

3

GCC provides many features as compiler extensions, off the top of mind and frequently used by me are:

Statement Expressions
Designated Initializers

There are many more documented on the GCC website here.

Caveat: However, using any form of compiler extensions renders your code non-portable across other compilers so do use them at that risk.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

If you want real-life examples of how useful gcc extensions can be then GCC hacks in the Linux kernel is an interesting choice since if it is being used in the Linux kernel then it is probably a good indication it has some real-world impact. As noted before, using extensions does make your code non-portable but clang does make an effort to support gcc extensions which may mitigate some of the impact.

One extensions that is not covered but is used a lot in the Linux kernel is statement expressions, also see Are compund statements (blocks) surrounded by parens expressions in ANSI C?.

The article covers the following features:

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

I recently stumbled over quite a lot of them that are really helpful to emulate the new C11 standard. Actually many of the new features are already there, but with different syntax.

  • alignment attributes
  • thread local variables
  • noreturn attribute to functions
  • atomic operations (through their __sync_... builtins)
  • type generic programming

I've written some of that and how to use that with the C11 interfaces in my blog.

Two features that are not covered in functionality by C11 that are really nice, and that I'd very much like to see in future versions of the standard

  • statement expressions (already mentioned by Als)
  • __typeof__
Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177