// 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上運行的結果為:
2、使用clang進行編譯
clang++ module1.cpp odr_test1.cpp
運行結果:
若進行下面的編譯:
clang++ odr_test1.cpp module1.cpp
則結果如下
3、使用gcc編譯
g++ module1.cpp odr_test1.cpp -std=c++11
若進行如下編譯
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;
}
運行結果
到此這篇關于C++ odr用法案例詳解的文章就介紹到這了,更多相關C++ odr用法內容請搜索html5模板網以前的文章希望大家以后多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!