简体   繁体   English

订单输入文件如何影响GCC中的链接和静态初始化?

[英]How does the order input files affect linkage and static initializaion in GCC?

Suppose I have the following files: 假设我有以下文件:

lib/Ah LIB /阿

#ifndef A_H
#define A_H

#include <vector>

class A {
        public:
                static int add( int x );
                static int size();
        private:
                static std::vector<int> vec;
};

#endif

lib/A.cpp LIB / A.cpp

#include "A.h"

std::vector<int> A::vec;

int A::add( int x ) {
        vec.push_back( x );
        return vec.size();
}

int A::size() { 
        return vec.size();
}

lib/Bh LIB / BH1

#ifndef B_H
#define B_H

class B {
        public:
                static const int val = 42;
};

#endif

lib/B.cpp LIB / B.cpp

#include "B.h"
#include "A.h"

int tempvar = A::add( B::val );

and finally: main:cpp 最后:主要:cpp

#include <iostream>
#include "lib/A.h"
#include "lib/B.h"

int main() {
        std::cout << A::size() << std::endl;
}

The result of this code differs depending on how I compile it: 此代码的结果因编译方式而异:

g++ main.cpp lib/A.cpp lib/B.cpp -o nolibAB
./nolibAB

prints "1" 打印“1”

g++ main.cpp lib/B.cpp lib/A.cpp -o nolibBA
./nolibBA

prints "0" 打印“0”

g++ -c lib/A.cpp lib/B.cpp
ar rvs lib.a A.o B.o
g++ main.cpp lib.a
./a.out

prints "0" (regardless if I reorder A.cpp and B.cpp) 打印“0”(无论我是否重新排序A.cpp和B.cpp)

Can someone tell me the reason that this is the case? 有人能告诉我这种情况的原因吗?

EDIT: I use gcc 4.6.1 编辑:我使用gcc 4.6.1

This is undefined by the standard. 标准未定义。 Simply put: You should not rely on global variables being initialized in a certain order. 简单地说:您不应该依赖于按特定顺序初始化的全局变量。

Related: Static initialization order issue in C++ 相关: C ++中的静态初始化顺序问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM