C++ odr用法案例詳解

// 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用法內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: