【问题标题】:Redefined variable in the other module在另一个模块中重新定义变量
【发布时间】:2014-04-22 04:20:34
【问题描述】:

为什么当我们在其他模块中重新定义变量时,可以将这些模块链接在一起?我编写了两个模块main.cppmodule.cpp,如下所示:

//--main.cpp--//
#include <stdio.h>

int main(){
    int i=5;
    printf("The value of i is %d",i);
}

//--module.cpp--//
int i=7;

现在我正在编译并将它们与g++ 链接如下:

g++ -c main.cpp
g++ -c module.coo
g++ -o bin main.o module.o

没关系。但我预计编译只会成功,而链接器会抛出像redefining varaible 这样的异常。当我运行./bin 时,输出为The value of i is 5

UPD:我知道如果我们将 i 声明为模块 main.cpp 的全局变量,链接器将抛出错误。

【问题讨论】:

    标签: c++ variables module redefinition


    【解决方案1】:

    在函数中,主变量 i 是函数的局部变量。它是不可见的,存在于函数之外。

    考虑以下示例

    #include <iostream>
    
    int i = 3;
    
    int main()
    {
       int i = 10
    
       std::cout << "i = " << i << std::endl;
       std::cout << "::i = " << ::i << std::endl;
    
       i = ::i;
    
       std::cout << "i = " << i << std::endl;
       std::cout << "::i = " << ::i << std::endl;
    
       {
            int i = 20;
    
            std::cout << "i = " << i << std::endl;
            std::cout << "::i = " << ::i << std::endl;
       }
    
       std::cout << "i = " << i << std::endl;
       std::cout << "::i = " << ::i << std::endl;
    }
    

    局部变量没有链接。

    【讨论】:

    • 感谢您的回答。但我有一个关于局部变量链接的问题。你能得到 cpp/ld 规范的参考吗?如果我在规范中正式阅读过这个对我来说会更好:)。
    • @DmitryFucintv 局部变量没有链接,所以你找不到任何提及它。
    • 好的,我明白了。
    • @3.5 程序和链接 您应该阅读 C++ 标准的“3.5 程序和链接”部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多