C++ odr用法案例詳解
更新時間:2021年09月13日 11:36:55 作者:會會會飛的魚
這篇文章主要介紹了C++ odr用法案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
// The main module. File: odr_test1.cpp #include <iostream> void module1_print(); // declaration of an exeternal function inline int f1() { return 4; } class A { public: static double f() { return 4.1; } }; const double C = 4.2; constexpr double E = 4.5; void print() { std::cout << "main f1(): " << f1() << std::endl; std::cout << "main A::f(): " << A::f() << std::endl; std::cout << "main C: " << C << std::endl; std::cout << "main E: " << E << std::endl; } int main() { module1_print(); print(); int i; std::cin >> i; }
// File: module1.cpp #include <iostream> inline int f1() { return 3; } class A { public: static double f() { return 3.1; } }; const double C = 3.2; constexpr double E = 3.5; void module1_print() { std::cout << "module1 f1(): " << f1() << std::endl; std::cout << "module1 A::f(): " << A::f() << std::endl; std::cout << "module1 C: " << C << std::endl; std::cout << "module1 E: " << E << std::endl; }
1、在VS2017上運行的結(jié)果為:
2、使用clang進(jìn)行編譯
clang++ module1.cpp odr_test1.cpp
運行結(jié)果:
若進(jìn)行下面的編譯:
clang++ odr_test1.cpp module1.cpp
則結(jié)果如下
3、使用gcc編譯
g++ module1.cpp odr_test1.cpp -std=c++11
若進(jìn)行如下編譯
g++ odr_test1.cpp module1.cpp -std=c++11
二、如何解決這個問題
// The main module. File: odr_test2.cpp #include <iostream> void module2_print(); // declaration of an external function namespace { inline int f1() { return 4; } class A { public: static double f() { return 4.1; } }; } const double C = 4.2; constexpr double E = 4.5; void print() { std::cout << "main f1(): " << f1() << std::endl; std::cout << "main A::f(): " << A::f() << std::endl; std::cout << "main C: " << C << std::endl; std::cout << "main E: " << E << std::endl; } int main() { module2_print(); print(); int i; std::cin >> i; }
// File: module2.cpp #include <iostream> namespace { inline int f1() { return 3; } class A { public: static double f() { return 3.1; } }; } const double C = 3.2; constexpr double E = 3.5; void module2_print() { std::cout << "module2 f1(): " << f1() << std::endl; std::cout << "module2 A::f(): " << A::f() << std::endl; std::cout << "module2 C: " << C << std::endl; std::cout << "module2 E: " << E << std::endl; }
運行結(jié)果
到此這篇關(guān)于C++ odr用法案例詳解的文章就介紹到這了,更多相關(guān)C++ odr用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解約瑟夫環(huán)問題及其相關(guān)的C語言算法實現(xiàn)
這篇文章主要介紹了詳解約瑟夫環(huán)問題及其相關(guān)的C語言算法實現(xiàn),也是ACM當(dāng)中經(jīng)常會引用到的基礎(chǔ)題目,文中共介紹了三種C語言解答,需要的朋友可以參考下2015-08-08