2010-11-21 75 views
1

(從加速C++兩者)由於嵌套的匿名塊,代碼不能編譯?

爲什麼下面的代碼無法正常工作:

#include <iostream> 
#include <string> 

int main() { 
    { 
     const std::string s = "a string"; 
     std::cout << s << std::endl; 

     { 
      const std::string s = "another string"; 
      std::cout << s << std::endl; 
     } 
    } 
} 

不允許我嵌套匿名塊在C++?當試圖編譯源,海灣合作委員會給了我下面的錯誤(我不能作出任何意義):

hello: In function `_start': 
(.text+0x0): multiple definition of 
`_start' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crt1.o:(.text+0x0): 
first defined here 
hello:(.rodata+0x0): multiple 
definition of `_fp_hw' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crt1.o:(.rodata+0x0): 
first defined here hello: In function 
`_fini': (.fini+0x0): multiple 
definition of `_fini' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crti.o:(.fini+0x0): 
first defined here 
hello:(.rodata+0x4): multiple 
definition of `_IO_stdin_used' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crt1.o:(.rodata.cst4+0x0): 
first defined here hello: In function 
`__data_start': (.data+0x0): multiple 
definition of `__data_start' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crt1.o:(.data+0x0): 
first defined here hello: In function 
`__data_start': (.data+0x4): multiple 
definition of `__dso_handle' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/crtbegin.o:(.data+0x0): 
first defined here hello: In function 
`_init': (.init+0x0): multiple 
definition of `_init' 
/usr/lib/gcc/i486-linux-gnu/4.4.3/../../../../lib/crti.o:(.init+0x0): 
first defined here /tmp/cchh83A6.o: In 
function `main': 
hello.cpp:(.text+0x0): multiple 
definition of `main' 
hello:(.text+0xb4): first defined here 
/usr/lib/gcc/i486-linux-gnu/4.4.3/crtend.o:(.dtors+0x0): 
multiple definition of `__DTOR_END__' 
hello:(.dtors+0x4): first defined here 
/usr/bin/ld: warning: Cannot create 
.eh_frame_hdr section, --eh-frame-hdr 
ignored. /usr/bin/ld: error in 
hello(.eh_frame); no .eh_frame_hdr 
table will be created. collect2: ld 
returned 1 exit status
+0

你用什麼命令來編譯和鏈接它?另外,如果你刪除了「匿名塊」,你是否仍然有錯誤? – 2010-11-21 19:07:57

+1

該錯誤似乎是在您的構建環境中,而不是在您的代碼中。請發佈一些關於您的IDE和構建設置(一個makefile?)的信息,並生成構建命令(您可能在發佈之前在控制檯中看到它)。 – Kos 2010-11-21 19:11:25

+0

命名(非匿名)塊的外觀是什麼? :) – fredoverflow 2010-11-21 19:26:58

回答

3

你似乎在鏈接2個或更多的定義相同事物的目標文件(或者.a文件)。如果你鏈接到一個或另一個鏈接器問題將消失。

+0

D'oh。你是對的,這是問題所在。它寫了'g ++ hello hello.cpp'而不是'g ++ -o hello hello.cpp'。 – helpermethod 2010-11-21 19:38:17