Note that there are some explanatory texts on larger screens.

plurals
  1. POgcc - 2 versions, different treatment of inline functions
    primarykey
    data
    text
    <p>Recently I've come across a problem in my project. I normally compile it in gcc-4, but after trying to compile in gcc-3, I noticed a different treatment of inline functions. To illustrate this I've created a simple example:</p> <p>main.c:</p> <pre><code>#include "header.h" #include &lt;stdio.h&gt; int main() { printf("f() %i\n", f()); return 0; } </code></pre> <p>file.c:</p> <pre><code>#include "header.h" int some_function() { return f(); } </code></pre> <p>header.h</p> <pre><code>inline int f() { return 2; } </code></pre> <p>When I compile the code in gcc-3.4.6 with:</p> <pre><code>gcc main.c file.c -std=c99 -O2 </code></pre> <p>I get linker error (multiple definition of f), the same if I remove the <code>-O2</code> flag. I know the compiler does not have to inline anything if it doesn't want to, so I assumed it placed f in the object file instead of inlining it in case of both <code>main.c</code> and <code>file.c</code>, thus multiple definition error. Obviously I could fix this by making <code>f</code> static, then, in the worst case, having a few <code>f</code>'s in the binary.</p> <p>But I tried compiling this code in gcc-4.3.5 with:</p> <pre><code>gcc main.c file.c -std=c99 -O2 </code></pre> <p>And everything worked fine, so I assumed the newer gcc inlined <code>f</code> in both cases and there was no function <code>f</code> in the binary at all (checked in gdb and I was right).</p> <p>However, when I removed the <code>-O2</code> flag, I got two undefined references to <code>int f()</code>. And here, I really don't understand what is happening. It seems like gcc assumed <code>f</code> would be inlined, so it didn't add it to the object file, but later (because there was no <code>-O2</code>) it decided to generate calls to these functions instead of inlining and that's where the linker error came from.</p> <p>Now comes the question: how should I define and declare simple and small functions, which I want inline, so that they can be used throughout the project without the fear of problems in various compilers? And is making all of them static the right thing to do? Or maybe gcc-4 is broken and I should never have multiple definitions of inline functions in a few translation units unless they're static?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload