2016-03-25 96 views
-5

我第一次真正使用#pragma,出于某种原因,我没有得到与在线发布的输出相同的输出,函数不打印出来,我使用GCC v5.3和clang v。3.7。这里的代码#pragma在C中无法正常工作?

#include<stdio.h> 

void School(); 
void College() ; 

#pragma startup School 105 
#pragma startup College 
#pragma exit College 
#pragma exit School 105 

void main(){ 
    printf("I am in main\n"); 
} 

void School(){ 
    printf("I am in School\n"); 
} 

void College(){ 
    printf("I am in College\n"); 
} 

我用“gcc file.c”和“clang file.c”编译。 我得到的输出是“I am in main”

+3

你在哪里找到的'[GCC文件]中的#pragma startup'和'的#pragma exit'(https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc /Pragmas.html)? –

+2

Pragma依赖于编译器,[GCC在线文档关于pragmas](https://gcc.gnu.org/onlinedocs/gcc/Pragmas.html)没有列出这些,所以它可能是Clang(其目的是为GCC兼容性)也没有它们。 [Visual C编译器没有这些编译指示](https://msdn.microsoft.com/en-us/library/d9x1s805.aspx)。快速搜索似乎表明它们特定于[Embarcadero C++ Builder](https://www.embarcadero.com/products/cbuilder)。 –

+0

http://stackoverflow.com/q/29462376/971127 – BLUEPIXY

回答

0

#pragma在编译器中不一致。它只是用于特定编译器/平台的奇怪情况。对于像这样的一般程序,它不应该被使用。

完成此操作的更好方法是使用#define和#if。例如:

#include<stdio.h> 

#define SCHOOL 1 
#define COLLEGE 2 

#define EDUCATION_LEVEL COLLEGE 

void None(); 
void School(); 
void College(); 

void main(){ 
    #if EDUCATION_LEVEL == SCHOOL 
     School(); 
    #elif EDUCATION_LEVEL == COLLEGE 
     College(); 
    #else 
     None(); 
    #endif 
} 

void None(){ 
    printf("I am in neither school nor college\n"); 
} 

void School(){ 
    printf("I am in School\n"); 
} 

void College(){ 
    printf("I am in College\n"); 
}