使用优化标志编译C代码

3
我正在比较两个C文件的两种汇编形式,一个带有优化标志(-O2),另一个没有。
我的问题是:
为什么在优化后的汇编版本中,编译器将主函数放在所有辅助函数之后,而在原始汇编代码中,辅助函数排在主函数之前。这在效率方面意味着什么?请有人详细解释一下。
以下是原始C文件。谢谢!
// Based on a source file found in a beginner's discussion on multidimensional arrays here:
// http://www.dreamincode.net/forums/topic/71617-3d-arrays/

#include <stdio.h>
#include <string.h>

int validColor( char *str );
int mathProblem( char *str );

// 1) Asks from six 'theoretical' different users one of two questions,
// allowing only three answers for each.
// 2) Stores the response into a multidimensional array

int main( void )
{
        char myArray[ 6 ][ 3 ][ 20 ]; /* Six users, three questions, and up to 19 characters per answer
(strings are '\0' terminated), though no "true" answer is that long */
        int i, valid;

/* User instructions */
        for( i = 0; i < 6; i++ )
        {
if ( i % 2 == 0 )
{
valid = 0;
while( valid == 0 )
{
                 printf( "Enter your favorite color : " );

                 fgets( myArray[ i ][ 0 ], 20, stdin ); /* Get answer to first question */

if( myArray[ i ][ 0 ][ 0 ] == '\n' ) /* If the user just presses enter, move to next question */
break; /* Jump out of while loop */

valid = validColor( myArray [i ][ 0 ] ); /* Call function to validate answer */
}
}
if ( i % 2 == 1 )
{
valid = 0;
while( valid == 0)
                        {
                                printf( "The roots of (x - 4)^2 : " );

                                fgets(myArray[ i ][ 0 ], 20, stdin); /* Get answer to second question */

                                if(myArray[ i ][ 0 ][ 0 ] == '\n') /* If the user just presses enter, move to next question */
                                        break; /* Jump out of while loop */

                                valid = mathProblem( myArray[ i ][ 0 ] ); /* Call function to validate answer */
                        }
}
        }

        return 0;
}

int validColor( char *str )
{
if( strcmp( str, "Black\n" ) == 0 )
return 1;
if( strcmp( str, "Red\n" ) == 0 )
return 1;
if( strcmp( str, "Blue\n" ) == 0 )
return 1;

return 0; /* If no match above, answer is not valid */
}

int mathProblem( char *str )
{
if ( atoi( str ) == 2 ) /* Function call for analysis purposes */
return 1;
if ( strcmp( str, "-2\n" ) == 0 )
return 1;
if ( strcmp( str, "+2\n" ) == 0 )
return 1;

return 0; /* If no match above, answer is not valid */
}

为了完全透明公开,您使用哪个编译器? - Mike Caron
5
“主函数在所有辅助函数之后”的写法和“辅助函数先出现”的写法有什么不同? - Bo Persson
2个回答

4

就效率而言,John是完全正确的。毕竟一切都被编译到一个目标文件中,函数只是符号表中的条目,顺序并不重要。

至于你提出的为什么会出现这样的顺序:

  • 没有进行优化时,对所有函数的调用只是对函数地址的引用。编译器可以轻松地按照遇到函数定义的顺序生成目标代码。
  • 优化时,编译器将所有对小函数的调用(至少潜在地)替换为内联代码,对于手头有定义的函数,它通常无法在遇到函数时直接生成代码,而必须等待直到它最终看到所有被调用的函数的声明。因此,发射顺序类似于调用图的反线性排序。

如果有什么问题,它也可能适得其反。如果在其之前有足够的代码,则指令更有可能被分解为不同的缓存行。 - Jeff Mercado
简而言之,这取决于编译器生成代码的顺序,与生成的代码效率无直接关系。 - Clifford

3

从效率上来说,这不会有实质性的区别。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接