Thomas Matthews wrote:
pooh wrote:
I have a situation where the order of my cpp files in my g++ compile
command line affects the program.
Here is a simplified example:
g++ -Wall -o test a.cpp b.cpp
compiles, links and runs fine.
g++ -Wall -o test b.cpp a.cpp
compiles, and links fine (no errors or warnings) but returns a
segmentation fault when run.
I did not think that the order of the files mattered.
g++ (GCC) 3.3.4 on Debian Linux 2.4.26-1-386
When linking, some linkers only perform a single pass.
This may have something to do with external dependencies,
things referenced outside of a given translation unit.
In some linkers, the object files have to be listed more
than once in order to satisfy undefined symbols.
Try this:
g++ -Wall -c -o a.o a.cpp
g++ -Wall -c -o b.o b.cpp
g++ -o test a.o b.o
also try this:
g++ -o test b.o a.o
I think found the cause of the problem but I'm uncertain as to the reason.
(Sorry but I'm new to c++ so my terminology below may not be quite accurate)
In one of my class headers (.h file) I have an extern statement to allow
the class to be initialized globally.
(in my A.h file):
class A
{ <snip> }
extern A gclA;
I initialize a global object using this class at the end of the
corresponding cpp file.
(in my A.cpp file):
<snip>
A gclA();
But if I switch the g++ command line order of A.cpp with one that is
dependent on it (B.cpp) the program compiles and links but generates a
segmentation fault when run. The opposite order works fine.
Today I found that if I move the initialization of the global object
from A.cpp to main.cpp (which contains the main() function) then the
order of A.cpp and B.cpp no longer causes a problem.
I guess the logic is simply that the program linking somehow determines
when my global object gets initialized and if I get the order wrong the
dependent code fails? Seems odd to me but then again, I think global
variables should be avoided (and this is maybe one of the many reasons
why?).
I'm tempted to pass all "globals" as parameters. Is this practical?
What is a "translation unit". That term is new to me (as is c++).
Thanks