Search code examples
cpragma

#pragma not working right in C?


my first time really working with #pragma and for some reason I don't get the same output as the ones posted online, the functions don't print out, I use GCC v5.3 and clang v. 3.7. Here's the code

#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");
}

and I compile with "gcc file.c" and "clang file.c". The output I get is "I am in main"


Solution

  • #pragma is not consistent across compilers. It is only meant to be used in odd situations with specific compilers/platforms. For a general program like this it should never be used.

    A better way to accomplish this is with #define and #if. For example:

    #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");
    }