Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the keyword "static" of Cpicket +

Shulou Source: shulou.com Published: 2022-06-01 12:02:23 10月03日 Update

This article mainly introduces the relevant knowledge of "how to use the keyword static of CAccord +". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope that this article "how to use the keyword static of CAccord +" can help you solve the problem.

Demonstration of hidden scenes in C language

When we compile multiple files at the same time, all global variables and functions without the static prefix have global visibility. Causes the symbol table to think that there is a collision between a global variable and a function with the same name.

Scenario: global variables / functions are owned in multiple .cc files in .h and are globally visible with link problems.

A.h

# pragma once#includevoid Test () {printf ("I am test..\ n");}

B.c

# include "a.h" void call () {Test ();}

C.c

# include "a.h" int main () {Test ();}

Makefile

All:cc:c.o b.o gcc-o $@ $^ c.o:c.c gcc-c $^ b.o:b.c gcc-c $^ .PHONY: cleanclean: rm-rf * .o c

Running result

At this point, view the b.o and c.o symbol tables. (readelf-s xxx.o)

You can see that both parties'.o symbol tables think that there is a Test of a GLOBAL global function, and the symbol tables formed in the assembly phase of the two sides will have a conflict of global functions with the same name at the summary stage.

At this point, both binaries are considered to have the Test () function, and both are global. Global functions can only have one name (note: overloading is renamed at the bottom). Although we know that the two Test () are the same, link thinks that there are two functions with the same name implemented, so an link error is reported.

Solution method

Separation of declaration and definition

Get into the habit of separating declaration from definition, and only declare no definition in .h. Defined in the .c file.

A.h

# includevoid Test ()

A.c

# include "a.h" void Test () {cout

Tags: Variable function global static member file object pattern function key keyword different memory symbol b. OQ. C. o program run two scenario Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Tech Info MySQL NVidia vpn