To initialize a static object across C + + files and libraries

Source: Internet
Author: User

Vacations are usually a good time to look back on the past. Here is a question that I was thinking about last month that made me "Ah-hah" for a moment.

Problem:

When you compile the following C + + program, you may think that the objects in the Modules (module) will be compiled and initialized first.

This assumption may not have the desired result.

X.h:

#include <string>

using namespace Std; The Translator notes: Add this line

Class Cobjet {

Public

static const string STRINGX;

};

X.cpp:

#include <X.h>

using namespace Std; Translator Note: This line can not

Const string COBJET::STRINGX = "001";

Y.cpp:

#include <iostream>

#include <X.h>

const string stringy= cobjet::stringx;

int main () {

cout << "Cobjet::stringx [" <<cobjet::stringx << "]" << Endl;

cout << "stringy [<< stringy <<"] "<< Endl;

return 0;

}

If you compile with the following command:

Xlc-c-i./X.cpp-o X.O

Xlc-c-i./Y.cpp-o y.o

Xlc-o binary X.O y.o

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.