Uttam Malakar
Uttam Malakar

Reputation: 714

Is #pragma directive compiler dependent?

I know and I've used #pragma startup and #pragma exit before but when I execute the following code it outputs only In main. Can anyone tell me what's happening here?

#include<stdio.h>
#pragma startup A 110
#pragma startup B
#pragma exit A
#pragma exit B 110

int main()
{
    printf("\nIn main");
    return 0;
}

void A()
{
    printf("\nIn A");
}

void B()
{
    printf("\nIn B");
}

Or is it compiler dependent? I am using gcc compiler.

Upvotes: 6

Views: 2095

Answers (4)

sandeep.ganage
sandeep.ganage

Reputation: 1467

As far as I know, gcc simply doesn't support the startup/exit pragma. You will have to use attribute to make it work with gcc.

__attribute__((constructor))
__attribute__((destructor))
__attribute__((constructor (PRIORITY)))
__attribute__((destructor (PRIORITY)))

This will work :

    #include<stdio.h>
    void A() __attribute__((constructor(110)));
    void B() __attribute__((constructor));
    void A() __attribute__((destructor));
    void B() __attribute__((destructor(110)));

    int main()
    {
        printf("\nIn main");
        return 0;
    }

    void A()
    {
        printf("\nIn A");
    }

    void B()
    {
        printf("\nIn B");
    }

Upvotes: 2

Norman Gray
Norman Gray

Reputation: 12514

All #pragma directives are compiler-dependent, and a compiler is obliged to ignore any it does not recognise (ISO-9899:2011, s6.10.6: “Any such pragma that is not recognized by the implementation is ignored.”). That's why your program compiles successfully.

Functions A and B aren't called because... you don't call them. Apologies if you understand this perfectly well, but: a C program is executed by invoking the function main. If you want the functions A and B to be called, you have to do so within the main function.

(In fact, recent versions of the C standard have introduced a small number of STDC pragmas which implementations are obliged to recognise, but that doesn't importantly affect the answer)

Upvotes: 5

Jerry Coffin
Jerry Coffin

Reputation: 490018

All #pragma directives are implementation defined. At one time, gcc responded to any and all #pragma directives in the same (generally undesirable) way.

Upvotes: 0

Mike Dinescu
Mike Dinescu

Reputation: 55720

Yes, the #pragma directive is compiler dependent.

More specifically, the supported options are compiler specific. Some options may be supported by many or most compilers but in many cases the options are specific to each compiler.

Upvotes: 2

Related Questions