0

我创建了两个文件,第二个文件应该打印一个 std::vector。

那是我的 main.cpp:

#include <vector>
int main() {

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
return 0;
}

那是 print.cpp

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

template <typename T> void printVec(T vec) {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}

template void printVec< std::vector<int> >(std::vector<int> t);

我编译了这些文件:

g++ -g main.cpp -o main.o
g++ -g -c print.cpp -o print.o
g++ -o main main.o print.o

并得到以下错误

main.o: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
main.o: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
main.o:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
main.o: In function `__data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
main.o: In function `__data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.6/crtbegin.o:(.data+0x0): first defined here
main.o: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.6/crtend.o:(.dtors+0x0): multiple definition of `__DTOR_END__'
main.o:(.dtors+0x8): first defined here
/usr/bin/ld: error in main.o(.eh_frame); no .eh_frame_hdr table will be created.
collect2: ld returned 1 exit status

我应该如何让它运行?

4

1 回答 1

6

改变:

g++ -g main.cpp -o main.o
g++ -g -c print.cpp -o print.o
g++ -o main main.o print.o

至:

g++ -g -c main.cpp -o main.o
g++ -g -c print.cpp -o print.o
g++ -o main main.o print.o

或者,您也可以将所有 3 个操作合二为一(并在操作时启用警告):

g++ -g -Wall -o main main.cpp print.cpp
于 2012-09-11T10:22:07.480 回答