2010-11-21 18 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

これをコンパイルしてリンクするためにどのようなコマンドを使用していますか?また、「匿名ブロック」を削除した場合でも、エラーはありますか? –

+1

あなたのコードではなく、あなたのビルド環境にエラーがあるようです。あなたのIDEとビルドのセットアップ(makefile?)と生成されたビルドコマンドについての情報を投稿してください(投稿した出力の直前にコンソールに表示されるかもしれません)。 – Kos

+0

名前の付いた(匿名ではない)ブロックはどのように見えますか? :) – fredoverflow

答えて

3

同じものを定義する2つ以上のオブジェクトファイル(または.aファイル)とリンクしているようです。リンカーの問題が解消されます。

+0

D'oh。そうです、これが問題でした。 'g ++ -o hello hello.cpp'の代わりに、' g ++ hello hello.cpp'を書きました。 – helpermethod

6

このコードは正常に動作します:ソースをコンパイルしようとすると、gccが私に(私はのいずれかの意味がありません)、次のエラーが発生します。ここをクリックしてくださいYour code compiled(環境に問題があります)

関連する問題