gpt4 book ai didi

c++ - 外部打印函数如何编译

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:43 24 4
gpt4 key购买 nike

我创建了两个文件,其中第二个文件应打印一个 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

我应该如何让它运行?

最佳答案

改变:

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

关于c++ - 外部打印函数如何编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com