C ++ declaration and definition

Source: Internet
Author: User

C ++ declaration and definition
C ++ declaration and definition

The Declaration is to introduce a name into the program. The definition provides a unique description of an object in the program. Declarations and definitions sometimes exist at the same time.

Such as int;

Extern int B = 1;

It is declared only when there is no initialization in extern. In other cases, it is both a definition and a declaration.

However, in the following cases, the statement is only a statement:

1: only provides the function prototype. For example, void func (int, int );

2: extern int;

3: class;

4: typedef Declaration

5: Declaration of static data members defined in the class

Class A {public: static int a; // declaration. };

In the following cases, the definition is just a definition:

1: In addition to the class definition, define and initialize a static data member. For example, A: a = 0;

2: Non-inline member functions are defined outside the class.

Declaration only introduces a symbol to a scope. The definition provides a unique description of an object in the program. It is acceptable to re-declare a symbol in a given definition field, but it cannot be defined repeatedly. Otherwise, compilation errors may occur. However, the member functions and static data members in the class are exceptional. Although they are declared in the class, there cannot be multiple members.

class A  {      public:      static int a;      static int a;      void func(int ,int);      void func(int ,int);  };

To understand the differences between declarations and definitions, you also need to understand internal links and external links.

During compilation, the compiler only checks whether the program syntax, functions, and variables are declared. If the function is not declared, the compiler will give a warning, but the target file can be generated. When linking a program, the linker will find the function implementation in all target files. If it cannot be found, the Link Error code (Linker Error) will be reported ). In VC, this error is generally the Link 2001 error, which means that the linker cannot find the function implementation.

Links link the symbols produced by different compilation units (pre-processed cpp files. There are two link Methods: internal link and external link.

If a symbolic name is local for its compilation unit and cannot conflict with the same name in other compilation units during the link, it is an internal link. The internal Link means that the access to this symbol is limited to the current compilation unit and is invisible to other compilation units.

When the static keyword is used as a global variable, it indicates a static global variable. However, the scope is only within the current file scope. Other files cannot be used even if the extern declaration is used. Similar to const.

Connections with static, const keywords, and enumeration types are internal.

Symbols with internal links cannot act on the external part of the current file. to affect other parts of the program, you can put them in. H files. At this time, all the source files that contain this. h file have their own definitions and do not affect each other.

The class definition has an internal link. Because it is a definition, it cannot be repeated in the same compilation unit. To be used in other compilation units, the class must be defined in the header file and included in other files. Class a is used only in other files. The declaration is not feasible because the class definition is an internal link and the symbols are not exported in the target file. It will not be parsed by other units for their undefined symbols. It is important to understand this.

Inline functions also have internal links.

In a multi-file program, if a symbol can interact with other compilation units during the link, this name has an external link. External links mean that this definition is not limited to a single compilation unit. It can generate external symbols in the. o file. It can be accessed by other compilation units to parse their undefined symbols. Therefore, they must be unique throughout the program; otherwise, repeated definitions may occur.

Non-inline member functions, non-inline functions, and non-static free functions all have external links.

All inline functions have internal links, because when possible, the compiler replaces all calls to the function with the function body and does not write any symbols into the. o file.

A good way to determine whether a symbol is an internal link or an external link is to check whether the symbol is written into the. o file.

The previous section describes the impact of definitions on the Link Method. Next, we will discuss the impact of declarations on the Link Method.

Since the Declaration is only useful to the current compilation unit, the Declaration does not write anything into the. o file.

For example, extern int a; int func ();

These declarations do not affect the content of the. o file. Each one is just an external symbol, so that the current compilation unit can access the corresponding global definition as needed.

Function call causes an undefined symbol to be written to the. o file. If a is not used in this file, it is not written to the. o file. The func function calls this function. This symbol is written to the target file. After that, the. o file and the. o file defining the symbol are connected, and the undefined symbol is parsed.

The preceding statement may cause the symbol to be written to the target file. However, the following statement does not cause this symbol to be written to the target file.

For example:

typedef int Int;Class A;  struct s;  union point;

Their links are also internal.

Both class declarations and class definitions are internal links. Only used for the current compilation unit.

The definition of static class data members has external links. For example

Class A {static int a; // declaration. Has an internal link. };

Static data member a is just A declaration, but its definition a: a = 0; has an external link.

C ++ processes classes and enumeration types differently. For example, you can declare a class when you do not define a class. However, an enumeration type cannot be declared without definition.

Based on the above analysis, we can know that it is almost a programming error to put the definition with external links in the header file. If the header file contains multiple source files, there will be multiple definitions and an error will occur during the link.

The definition of placing an internal link in the header file is legal, but it is not recommended. When the header file is included in multiple source files, it will not only pollute the global namespace, but also have its own entity in each compilation unit. A large amount of memory space is consumed, which also affects machine performance.

The global variables modified by const and static are only valid in the current file scope. They have internal link attributes.

The following lists some definitions that should or should not be written into the header file:

// Test. h # ifndef TEST_H # define TEST_H int a; // a has an external link and cannot be defined in the header file. Extern int B = 10; // same as above. Const int c = 2; // c has an internal link, which can be included in the header file but should be avoided. Static int d = 3; // same as above. Static void func () {}// same as above. Void func2 () {}// same as. Void func3 (); // yes. Only declaration. The symbol name is not written into the target file. Class A {public: static int e; // yes, with internal links. Int f; // Yes, same as above. Void func4 (); // declaration, internal link. Same as above. }; A: e = 10; // the header file cannot contain definitions with external links. Do not write the symbol name into the target file. Void A: func4 () // No, class member function. External Connection. {//,...} # Endif

I believe you understand why it is legal to declare a member function only in the type, rather than implement it. You can also explain why class definitions can be placed in. H files. Classes can be implemented in cpp files with the same name. The instructor previously introduced that the compiler will automatically search for cpp files with the same name. In fact, because the cpp file stores the implementation of member functions, and the member functions have the external link feature, it will generate symbols in the target file. This symbol is defined in this file. Other target files that call this function also generate an undetermined symbol. After the two target files are connected, the symbol is parsed. Note that static data members should be stored in the cpp file. But cannot be placed in. H files.

Definitions with internal links can be defined in the cpp file without affecting the global symbolic space. However, in the scope of the cpp file, avoid defining (not forbidden) data and functions that are not declared as static because they have external links.

For example

int a;  void func()  {       ......  }

If the above definition has an external link, it may conflict with other symbol names in the global namespace. If you need to use global variables or functions. You can add the static keyword to them. So that its scope is limited to the current file, with internal links will not affect the global namespace. Because inline and static free functions, enumeration, and const data have internal links, they can be defined in the cpp file without affecting the global namespace.

Typedef and macro definitions do not introduce symbols into the. o file. They can also appear in the cpp file without affecting the global namespace.

Typedef creates an alias for an existing type. Instead of creating a new type. It does not provide type security. For example

typedef int IntA;  typedef int InB;  

 

If you use IntB where IntA is needed, no error will be reported. They can be replaced with each other. This is because it does not provide type security. However, typedef is often used when defining function types to make the definition clearer.

The standard c Library provides an assert macro to ensure that the given expression value is non-zero. Otherwise, an error message is output and the program execution is terminated. Assert works only when NDEBUG is not defined in the program. Once NDEBUG is defined, the assert statement is ignored. Note that it is different from ASSERT in VC. ASSERT is provided by vc. It takes effect only when _ DEBUG is defined.

In the DEBUG mode of vc, _ DEBUG is defined. In the RELEASE mode, NDEBUG is defined.

For more information, see Large Scale C ++ software design.


What is the difference between declaration and definition in C language?

The Declaration tells the compiler that there is such a variable, but it is not implemented. The definition is to implement this variable and allocate space for this variable in the memory (heap or stack ).

C language Declaration definition

No error.

Only the Declaration and definition statements of all variables must be prior to other execution statements.
Here int num = 10; it is also a definition statement, not a value assignment statement.

It seems that this rule was only available in the earlier C language version. Later, the C language specification has no such requirement.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.