我有一個struct,其中定義了一個常量char字符串,並且指向了我自己的字符串對象。目標是聲明這個結構體的變量,其中字符集和txt設置爲NULL,並且在運行時創建表示字符的MyString對象。我在編譯期間無法創建MyString,而使用GLib,並且此庫首先需要調用g_type_init。mingw const char字符串顯然不是const
struct _MyStaticString {
volatile MyString * txt;
const char *chars;
};
的聲明會再看看這樣的:
struct _MyStaticString my_test_string = { NULL, "Hello world or foo bar, or a rick roll" };
那麼他們是一個函數,它是repsonsible通過第一檢查交付我的MyString的對象,如果TXT爲NULL,如果是創建一個新的MyString對象並返回這個MyString對象。
struct _MyString *my_static_string(struct _MyStaticString *a_static) {
printf("a_static=%lx\n", (gulong) a_static);
printf("a_static.chars=%s\n", (char *) a_static->chars);
if (a_static->txt == NULL) {
CatString *result = g_object_new(MY_TYPE_STRING, NULL);
// result->data = (gchar *) a_static->chars;
result->data = strdup((char *) a_static->chars);
result->size = strlen((char *) a_static->chars);
result->hash = 0;
g_object_ref_sink(G_OBJECT(result));
result->parent.ref_count = 1000;
a_static->txt = result;
}
return (struct _MyString *) (a_static->txt);
}
這一切的偉大工程,我很高興,至少當我在Linux上運行GCC。只要我在MinGW編譯器的幫助下開始在Windows上編譯此代碼,就會出錯。如果我把所有東西放在一個項目中它仍然沒問題,但只要將聲明放入.a庫並在其他地方使用,字段a_static-> chars就會變爲NULL。所以我開始播放/調整/測試:我想也許這是對象文件中數據的對齊,並因此添加了#pragma pack(16)。它沒有工作。比我想也許有一個屬性可以幫助我。所以我加了__attribute__
((普通))。它沒有工作。我認爲是聰明和分離從結構聲明本身喜歡的字符串:
const char helper_txt = "Hello world or foo bar, or a rick roll";
struct _MyStaticString my_test_string = { NULL, helper_txt };
我得到的編譯錯誤:
error: initializer element is not constant
error: (near initialization for 'field.chars')
這裏是我的編譯器標誌
C:\MinGW\bin\gcc.exe
-IC:\MinGW\include
-IC:\GTK_ALL_IN_ONE\include\gtk-2.0
-IC:\GTK_ALL_IN_ONE\lib\gtk-2.0\include
-IC:\GTK_ALL_IN_ONE\include\atk-1.0
-IC:\GTK_ALL_IN_ONE\include\cairo
-IC:\GTK_ALL_IN_ONE\include\gdk-pixbuf-2.0
-IC:\GTK_ALL_IN_ONE\include\pango-1.0
-IC:\GTK_ALL_IN_ONE\include\glib-2.0
-IC:\GTK_ALL_IN_ONE\lib\glib-2.0\include
-IC:\GTK_ALL_IN_ONE\include
-IC:\GTK_ALL_IN_ONE\include\freetype2
-IC:\GTK_ALL_IN_ONE\include\libpng14
-IC:\work\workspace\module-blah\src
-O0 -g3 -Wall -c -fmessage-length=0 -mms-bitfields -DOSWINDOWS
和這裏版本
C:\>c:\MinGW\bin\gcc.exe --version
gcc.exe (GCC) 4.5.0
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我錯過了一些編譯器標誌,還是需要添加一個屬性來確保const char *字符串被導出到.a庫中,並且它們是檢查天氣中字符串是否位於.a庫中的簡單方法?或者它可能是一些鏈接器選項?
您正在使用保留的標識符:C中任何以下劃線開頭並帶有大寫字母的標識符都被保留用於實現(見標準7.1.3),因此該程序會調用未定義的行爲。我的規則永遠不會以下劃線開始我的標識符。 – 2010-12-13 21:37:30
另外,你的意思是「字段a_static->字符變爲NULL」?具體發生了什麼?那是'const char helper_txt'還是正確的'const char * helper_txt'? – 2010-12-13 21:44:32