2012-02-22 11 views
6

Estoy tratando de reemplazar algunas subrutinas macro con funciones en línea, por lo que el compilador puede optimizarlas, por lo que el depurador puede entrar en ellas, etc. Si las defino como funciones normales, funciona:C funciones en línea y error "indefinido externo"

void do_something(void) 
{ 
    blah; 
} 

void main(void) 
{ 
    do_something(); 
} 

pero si los defino como en línea:

inline void do_something(void) 
{ 
    blah; 
} 

void main(void) 
{ 
    do_something(); 
} 

que dice "Error: Indefinido externa". Qué significa eso? Tomando una puñalada en la oscuridad, intenté

static inline void do_something(void) 
{ 
    blah; 
} 

void main(void) 
{ 
    do_something(); 
} 

y no más errores. La definición de función y la llamada a la función están en el mismo archivo .c.

¿Alguien puede explicar por qué uno funciona y el otro no?

(pregunta relacionada En segundo lugar: ¿Dónde pongo las funciones en línea si quiero usarlos en más de un archivo .c?)

+0

Es claro dónde estás poniendo esas definiciones, y cuando usted está recibiendo esos errores. ¿Hay algo de eso en los encabezados? ¿Avanza declarando en un encabezado e intentando usarlo desde otra unidad de compilación? – Mat

+0

Oh, las definiciones de función y la llamada a la función están ambas en el mismo archivo .c. – endolith

+0

¿Puedes publicar un [sscce] (http://pscode.org/sscce.html)? (Bueno, no compilable, por supuesto, en este caso.) – Mat

Respuesta

9

Primero, el compilador no siempre alinea las funciones marcadas como inline; por ejemplo, si desactiva todas las optimizaciones, probablemente no las alineará.

Cuando se define una función en línea

inline void do_something(void) 
{ 
    blah 
} 

y utilizar esa función, incluso en el mismo archivo, la llamada a esa función se resuelve por el enlazador no el compilador, ya que es implícitamente "externo". Pero esta definición sola no proporciona una definición externa de la función.

Si se incluye una declaración sin inline

void do_something(void); 

en un archivo de C que puede ver la definición inline, el compilador proporcionará una definición externa de la función, y el error debería desaparecer.

La razón static inline obras es que hace la función visible sólo dentro de esa unidad compilatioin, y así permite que el compilador para resolver la llamada a la función (y optimizarlo) y emiten el código de la función dentro de esa unidad de compilación. El vinculador entonces no tiene que resolverlo, por lo que no hay necesidad de una definición externa.

El mejor lugar para poner la función en línea es en un archivo de encabezado, y declararlos static inline. Esto elimina la necesidad de una definición externa, por lo que resuelve el problema del vinculador. Sin embargo, esto hace que el compilador emita el código para la función en cada unidad de compilación que lo utilice, por lo que podría provocar una saturación del código. Pero dado que la función está en línea, probablemente sea pequeña de todos modos, por lo que generalmente no es un problema.

La otra opción es definen como extern inline en la cabecera, y en un archivo de C proporcionar y externdeclaración sin el modificador inline.

El manual de gcc lo explica así:

By declaring a function inline, you can direct GCC to make calls to that function faster. One way GCC can achieve this is to integrate that function's code into the code for its callers. This makes execution faster by eliminating the function-call overhead; in addition, if any of the actual argument values are constant, their known values may permit simplifications at compile time so that not all of the inline function's code needs to be included. The effect on code size is less predictable; object code may be larger or smaller with function inlining, depending on the particular case. You can also direct GCC to try to integrate all "simple enough" functions into their callers with the option -finline-functions .

GCC implements three different semantics of declaring a function inline. One is available with -std=gnu89 or -fgnu89-inline or when gnu_inline attribute is present on all inline declarations, another when -std=c99 , -std=c1x , -std=gnu99 or -std=gnu1x (without -fgnu89-inline), and the third is used when compiling C++.

To declare a function inline, use the inline keyword in its declaration, like this:

static inline int 
inc (int *a) 
{ 
    return (*a)++; 
} 

If you are writing a header file to be included in ISO C90 programs, write __inline__ instead of inline .

The three types of inlining behave similarly in two important cases: when the inline keyword is used on a static function, like the example above, and when a function is first declared without using the inline keyword and then is defined with inline , like this:

extern int inc (int *a); 
inline int 
inc (int *a) 
{ 
    return (*a)++; 
} 

In both of these common cases, the program behaves the same as if you had not used the inline keyword, except for its speed.

When a function is both inline and static , if all calls to the function are integrated into the caller, and the function's address is never used, then the function's own assembler code is never referenced. In this case, GCC does not actually output assembler code for the function, unless you specify the option -fkeep-inline-functions . Some calls cannot be integrated for various reasons (in particular, calls that precede the function's definition cannot be integrated, and neither can recursive calls within the definition). If there is a nonintegrated call, then the function is compiled to assembler code as usual. The function must also be compiled as usual if the program refers to its address, because that can't be inlined.

Note that certain usages in a function definition can make it unsuitable for inline substitution. Among these usages are: use of varargs, use of alloca, use of variable sized data types , use of computed goto, use of nonlocal goto, and nested functions. Using -Winline will warn when a function marked inline could not be substituted, and will give the reason for the failure.

As required by ISO C++, GCC considers member functions defined within the body of a class to be marked inline even if they are not explicitly declared with the inline keyword. You can override this with -fno-default-inline .

GCC does not inline any functions when not optimizing unless you specify the always_inline attribute for the function, like this:

/* Prototype. */ 
inline void foo (const char) __attribute__((always_inline)); 

The remainder of this section is specific to GNU C90 inlining.

When an inline function is not static , then the compiler must assume that there may be calls from other source files; since a global symbol can be defined only once in any program, the function must not be defined in the other source files, so the calls therein cannot be integrated. Therefore, a non- static inline function is always compiled on its own in the usual fashion.

If you specify both inline and extern in the function definition, then the definition is used only for inlining. In no case is the function compiled on its own, not even if you refer to its address explicitly. Such an address becomes an external reference, as if you had only declared the function, and had not defined it.

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 will cause most calls to the function to be inlined. If any uses of the function remain, they will refer to the single copy in the library.

+0

"Primero, el compilador no siempre alinea las funciones marcadas como en línea" Sí, pero ¿No es mejor dejar que el compilador decida en lugar de forzarlo con macros? "Esto hace que el compilador emita el código para la función en cada unidad de compilación que lo usa". Pero si no se utiliza en ese archivo, no se compila, ¿o sí? Aquí hay restricciones de tamaño de código compiladas. – endolith

+1

"Sí, pero ¿no es mejor dejar que el compilador decida en lugar de forzarlo con macros?" No entiendo esta pregunta. "Pero si no se utiliza en ese archivo, no se compila, ¿o sí?" Está compilado, pero el código de la máquina no se emite; es esencialmente "desechado". –

0

Hay que ponerlos en un archivo de cabecera si desea utilizarlas desde archivos múltiples

Y para el error del enlazador: la declaración predeterminada de una función implica que es "extern", pero como está en línea, el enlazador puede encontrar el trozo de símbolo generado por el compilador, de ahí el error.

1

Para inline funciones para trabajar con C99 (que sólo llegó allí a la lengua) que tendría que dar a la definición contenida en un archivo de cabecera

inline void do_something(void) 
{ 
    blah 
} 

y en una unidad compilación (aka .c) se coloca una especie de "instanciación"

void do_something(void); 

sin la inline.

+1

De acuerdo. Parece que hay una pregunta similar aquí. http://stackoverflow.com/questions/6312597/is-inline-without-static-or-extern-ever-useful-in-c99 –