栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

变量名的存放和extern “C“的影响

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

变量名的存放和extern “C“的影响

在stackoverflow上找的比较好的回答,属于个人笔记,

一 代码中变量名的存放

All kinds of global, static and initialized constant variables are stored in the initialized data segment where as all the uninitialized ones are stored in the uninitialized data segment, also known as BSS (Block Started by Symbol). Local constants and variables defined in main() and pointers are stored in the stack. Rest which are allocated by malloc(), calloc() and so on are stored in the heap.

PS: There are some edge cases but I’m not going to talk about them for the sake of keeping this answer straightforward.

Now to your question
When you compile your code, C compilers create something known as a symbol table, which stores the relationship between variables and where the variable is located in memory. So, if you have declared a variable like

int abcd = 1234;

abcd itself (as in, the string “abcd”) is not stored anywhere. It doesn’t exist after your code is compiled, only its value remains. Variable names just exist for your convenience and after all, a compiler’s job is to translate your code to native machine code. In machine code, abcd’s value is just retrieved from its memory location using a movl instruction.

TL;DR: Variable names just exist for programming convenience and doesn’t exist post-compilation, only its memory location does.

也就是编译后,程序中就不包含变量名了,变量名只存在编译器生成的符号表里。


二 extern "C"的影响

extern “C” doesn’t really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

What extern “C” does is affect linkage. C++ functions, when compiled, have their names mangled – this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

Code inside an extern “C” is still C++ code. There are limitations on what you can do in an extern “C” block, but they’re all about linkage. You can’t define any new symbols that can’t be built with C linkage. That means no classes or templates, for example.

另外,本人测试发现extern "C"中定义的结构体,放到C++代码里是可以使用new去创建的,也就是变成了C++里的struct类型。

例如定义mystruct.h如下,

#ifndef _MY_STRUCT_H_
#define _MY_STRUCT_H_

#ifdef __cplusplus
extern "C" {
#endif

struct MyStruct
{
    int data1;
    int data2;
};

#ifdef __cplusplus
}
#endif


#endif

main.cpp如下,

#include 

#include "mystruct.h"


int main(int, char**) {

    MyStruct * mystr = new MyStruct;

    mystr->data1 = 100;

    std::cout << "data1: " << mystr->data1 << "n";

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号