#Function inlining for gnu17

16 messages · Page 1 of 1 (latest)

royal birch
#

I'm compiling my code with the -std=gnu17 flag, and from what I've inferred, it follows the gnu89 inline semantics.

According to the GCC manual:

This combination of inline and extern has almost the effect of a macro. The way to use it is to put a function definition in a header file with these keywords, and put another copy of the definition (lacking inline and extern) in a library file. The definition in the header file causes most calls to the function to be inlined. If any uses of the function remain, they refer to the single copy in the library.

In foo.h:

extern inline int bar(int src)
{
  int dst;
  asm ("mov %1, %0\n\t"
      "add $1, %0"
      : "=r" (dst)
      : "r" (src));
  return dst;
}

In foo.c:

#include "foo.h"

int bar(int src)
{
  int dst;
  asm ("mov %1, %0\n\t"
      "add $1, %0"
      : "=r" (dst)
      : "r" (src));
  return dst;
}

In test.c:

#include <stdio.h>
#include "foo.h"

int main()
{
  int a = 1;

  printf("%d\n", bar(a));

  return 0;
}

I get the following error on compiling with gcc -std=gnu17 foo.c test.c:

foo.c:3:5: error: redefinition of 'bar'
    3 | int bar(int src)
      |     ^~~
In file included from foo.c:1:
foo.h:1:19: note: previous definition of 'bar' with type 'int(int)'
    1 | extern inline int bar(int src)
      |                   ^~~
urban robinBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

tranquil beacon
#

I dont get the part where it said

If any uses of the function remain, they refer to the single copy in the library.

#

Ok I got that

#

Try explicitly mentioning extern on the definition present in foo.c file

#

;compile c -std=gnu89

extern inline int bar(int src)
{
  int dst;
  asm ("mov %1, %0\n\t"
      "add $1, %0"
      : "=r" (dst)
      : "r" (src));
  return dst;
}

int bar(int src)
{
  int dst;
  asm ("mov %1, %0\n\t"
      "add $1, %0"
      : "=r" (dst)
      : "r" (src));
  return dst;
}


#include <stdio.h>

int main()
{
  int a = 1;

  printf("%d\n", bar(a));

  return 0;
}
delicate estuaryBOT
#
Program Output
2
tranquil beacon
royal birch
#

I can't seem to find the right way to do it for any version other than gnu89

royal birch
#

@tranquil beacon so compiling with both the -std=gnu17 -fgnu89-inline seems to be working

#

Whether or not the function is actually inlined or not though, is another story

#

I either have to either

  1. Use __attribute__( ( always_inline ) ) with the .h inline declaration
  2. Compile with the -O3 flag
  3. Compile with the -finline-functions flag
royal birch
#

!closed