1

让我们考虑两种情况:

1.) 静态全局变量。当我生成地图文件时,我在 .bss 或 .data 部分中找不到静态全局变量。

2.) 静态成员

    #include <stdio.h>
    #include <iostream>
    #include <vector>
    #include <list>
    #include <algorithm>

    using namespace std;

    class Tree {
        struct Node {
            Node(int i, int d): id(i), dist(d) {}
            int id;
            int dist; // distance to the parent node
            list<Node*> children;
        };

        class FindNode {
            static Node* match;
            int id;
        public:
            FindNode(int i): id(i) {}
            Node* get_match()
            {
                return match;
            }

            bool operator()(Node* node)
            {
                if (node->id == id) {
                    match = node;
                    return true;
                }
                if (find_if(node->children.begin(), node->children.end(), FindNode(id)) != node->children.end()) {
                    return true;
                }
                return false;
            }
        };

        Node* root;

        void rebuild_hash();
        void build_hash(Node* node, Node* parent = 0);

        vector<int> plain;
        vector<int> plain_pos;
        vector<int> root_dist;
        bool hash_valid; // indicates that three vectors above are valid

        int ncount;
    public:
        Tree(): root(0), ncount(1) {}
        void add(int from, int to, int d);
        int get_dist(int n1, int n2);

    };

    Tree::Node* Tree::FindNode::match = 0;
...

变量 Tree::FindNode::match 是 FindNode 类的静态成员。此变量显示在 bss 部分的映射文件中。为什么这样??

 *(.bss)
 .bss           0x00408000       0x80 C:\Users\Администратор\Desktop\яндекс\runs\runs\\000093.obj
                0x00408000                _argc
                0x00408004                _argv
                0x00408020                Tree::FindNode::match

我用的是MinGW,os windows 7。g++ ...cpp -o ...obj命令得到的所有object文件,ld ....obj -Map .....map命令得到的map文件

4

1 回答 1

5

全局变量已经在静态内存中,因此 C 重新使用现有的关键字static来制作全局变量“文件范围”,C++ 遵循套件。关键字static从地图文件中隐藏您的全局。

Static members, on the other hand, are class-scoped, therefore they need to be available in the map file: other modules need to be able to access the static members of your class, both member functions and member variables, even if they are separately compiled.

于 2012-08-12T21:49:29.483 回答