What is name mangling, and how does it work?

Viewed 23577

Please explain what is name mangling, how it works, what problem it solves, and in which contexts and languages is used. Name mangling strategies (e.g. what name is chosen by the compiler and why) a plus.

10 Answers

At the time that link editors were designed, languages such as C, FORTAN and COBOL did not have namespaces, classes, members of classes and such other things. Name mangling is required to support object-oriented features such as those with a link editor that does not support them. The fact that the link editor does not support the additional features is often missed; people imply it by saying that name mangling is required due to the link editor.

Since there is so much variation among language requirements to support what name mangling does, there is not a simple solution to the problem of how to support it in a link editor. Link editors are designed to work with output (object modules) from a variety of compilers and therefore must have a universal way to support names.

All previous answers are correct but here is the Python perspective/reasoning with example.

Definition

When an variable in a class has a prefix of __ (i.e. two underscore) & does not have a suffix of __ (i.e. two underscore or more) then it's considered private identfier. Python interpreter converts any private identifier and it mangles the name to _class__identfier

Example:
MyClassName --> _myClassName
__variable --> __variable

Why

This is needed because to avoid problems that could be caused by overriding attributes. In other words, in order to override, the Python interpreter has to be able to build distinct id for child method versus parent method and using __ (double underscore) enable python to do this. In below example, without __help this code would not work.

class Parent:
    def __init__(self):
       self.__help("will take child to school")
    def help(self, activities):
        print("parent",activities)

    __help = help   # private copy of original help() method

class Child(Parent):
    def help(self, activities, days):   # notice this has 3 arguments and overrides the Parent.help()
        self.activities = activities
        self.days = days
        print ("child will do",self.activities, self.days)


# the goal was to extend and override the Parent class to list the child activities too
print ("list parent & child responsibilities")
c = Child()
c.help("laundry","Saturdays")

the answers here are awesome so this is just an addition from my little experience: i use name mangling in order to know , what tools ( gcc / vs /...) and how parameters passed into the stack and what calling convention i'm dealing with, and that based on the name so for example if see _main i know it's a Cdecl the same for others

Related