2013-12-10 60 views
0

當我編譯下面這段代碼優化啓用未使用變量警告

double bitrate = 8 * m_totBytes/(Simulator::Now() - m_startTime).GetSeconds(); 
double instBitrate = 8 * message.GetSize()/(Simulator::Now() - m_lastRecv).GetSeconds(); 
normBitrate = 0.1 * instBitrate + 0.9 * m_resolution; 

NS_LOG_INFO("------RECEIVED: " << message.GetSize() 
     << " Bitrate = " << bitrate 
     << " instBit = " << instBitrate 
     << " normBit = " << normBitrate); 

我得到一個編譯器警告說:

error: unused variable ‘bitrate’ [-Werror=unused-variable] 

因爲NS_LOG_INFO宏由編譯器進行優化。爲了編譯我必須添加的代碼無用的和醜陋的有點像如下:

if (false) { // For suppressing "Unused variable" warning when compiling with "-d optimiized" 
    std::cout << bitrate << instBitrate << normBitrate << std::endl; 
} 

我怎麼能編譯它沒有禁用警告,優化,並沒有垃圾代碼?

+3

也許添加一個'(無效)比特率;'聲明。 –

+0

如果定義了「NS3_LOG_ENABLE」,或者沿着這些線,只計算「比特率」怎麼樣?然後你的代碼實際上會被優化(不做一個不需要的計算)。 –

+0

@ Cheersandhth.-Alf是的工作。仍然添加一些垃圾代碼,但這看起來好多了 – user000001

回答

3

既然你不使用這個變量,除了在該情況下,爲什麼不只是做:

NS_LOG_INFO("------RECEIVED: " << message.GetSize() 
    << " Bitrate = " << (8 * m_totBytes/(Simulator::Now() - m_startTime).GetSeconds()) 
    << " instBit = " << instBitrate 
    << " normBit = " << normBitrate); 
+0

是的,這工作。仍然對泰勒的建議感興趣,以便只在必要時執行計算。 – user000001

+0

你沒有規定垃圾鱈魚,所以我堅持這個簡要說明,檢查當然應該工作的定義:-) – splrs

+1

@ user000001以及計算是在一個宏被擴大到沒有,所以這基本上是做我在說什麼,沒有額外的變量聲明,這可能更乾淨。如果因爲某種原因需要變量聲明,我相信你可以使用'#ifdef NS3_LOG_ENABLE'。 –