Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
20 years ago

C++ global objects

The NiosII linker fails to call constructors for static global objects.

A simple example:

test.h:# include <math.h>

const double PI = 3.14159265;

class Circle

{

protected:

double radius;

public:

Circle(double = 1.0);

double calcval();

};

test.cxx:# include "test.h"

Circle::Circle(double r)

{

radius = r;

}

double Circle::calcval(void)

{

return(PI * radius * radius);

}

testprog.cxx:# include <stdlib.h># include <stdio.h># include "test.h"

static Circle circle_1(10);

int main()

{

printf("The area of circle_1 is %f\n", circle_1.calcval());

exit (0);

}

This fails. Circle_1 will always be 0. Putting the declaration inside main works:

int main()

{

Circle circle_1(10);

printf("The area of circle_1 is %f\n", circle_1.calcval());

exit (0);

}

Have anyone else experienced this ? Is it a g++ or ld bug, or do there exist any magic compiler/linker flags that I&#39;m missing ?

(The example code works fine with gcc 3.4.1 on x86).

4 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Apparently there is something wrong with the linker script. I&#39;m using the default linker script shipped with the Microtronix uClinux port (elf2flt.ld). Are there any linker script gurus here ?

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Do you have the compiler option -mctors-in-init? You might also want the library -lsupc++

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Thanks! Adding -mctors-in-init to LDFLAGS did the trick. Can&#39;t find this compiler option documented anywhere. Is it an arch specific option ?

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    It is a Nios II specific option, but I did not find anything about it in Altera&#39;s document.