2014-04-30 47 views
0

我希望全局變量是常量,但它們應該在mexFunction()函數中定義。這是因爲它們應該設置爲來自Matlab的一些輸入值。 (mexFunction()基本上是我的main()函數)。C中共享的全局const變量,在mexFunction()中定義

這樣的事情有可能嗎?

main.h

extern int const myConstGlobal; 

的main.c

mexFunction(input) 
{ 
    int const myConstGlobal = input; 
} 

functions.c

#include main.h 

foo(myConstGlobal){} 

從我有我目前的理解有些鏈接:

如何與共享的Globa一起工作l變量在shared-global-variables-in-C中解釋。

如何使用共享的全局變量,常量工作,the second answer of this link

解釋......你必須聲明:

的extern INT常量CONST_INT;

在報頭中,並且:

的extern INT常量CONST_INT = FN();

在一個(且只有一個)源文件中。

但這樣我需要傳遞輸入值的函數,我想繞過。

+0

你必須把它的定義放在一個函數之外。否則它不是全球性的。 –

回答

0

JaBe - 我對Const的理解是它不能改變,它是一個固定的設定值。

這就是說,這是正確的?你應該能夠獲得const的地址並將其放置在一個指針中。

int * myConstGlobalPointer =&myConstGlobal;

如果編譯器是原諒的,並讓你這樣做,你可以設置myConstGlobalPointer = input; 這應該設置myConstGlobal的值。

訣竅是不把const指針調用一個const指針,這可能會工作。

Tim