2016-03-25 138 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"); 
}