[問題] link c with compiled c++ code [solved]
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Ubuntu 12.04 Server
問題(Question):
我想要用 gcc link c 和 c++ file
但是總是無法連到 stdc++ (undefined reference to std::...)
有一份 c code 和一份 c++ code
先用 g++ compile c++ code
g++ -c cpp_lib.cpp -o cpp_lib.o
再用 gcc compile c code
gcc -c c_main.c -o c_main.o
最後用 gcc 將兩者 link 起來的時候出錯
gcc -lstdc++ c_main.o cpp_lib.o -o c_main
我的 ubuntu 12.04 是用 virtualbox 灌好後,
只有 apt-get install g++ make 而已
在另一個架好的 gentoo server 上只要加上 -lstdc++ 就 link 的到了
但是在 ubuntu 上一直失敗, 不知道是不是缺少什麼東西?
錯誤結果(Wrong Output):
gcc -c c_main.c -o c_main.o
g++ -c cpp_lib.cpp -o cpp_lib.o
gcc -lstdc++ c_main.o cpp_lib.o -o c_main
cpp_lib.o: In function `test()':
cpp_lib.cpp:(.text+0xa): undefined reference to `std::cout'
cpp_lib.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
cpp_lib.o: In function `__static_initialization_and_destruction_0(int, int)':
cpp_lib.cpp:(.text+0x38): undefined reference to `std::ios_base::Init::Init()'
cpp_lib.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status
make: *** [c_main] Error 1
程式碼(Code):(請善用置底文網頁, 記得排版)
c_main.c:
int main()
{
return 0;
}
---------
cpp_lib.cpp:
#include <iostream>
void test()
{
std::cout << "test\n";
}
---------
Makefile:
c_main: c_main.o cpp_lib.o
gcc -lstdc++ c_main.o cpp_lib.o -o c_main
c_main.o: c_main.c
gcc -c c_main.c -o c_main.o
cpp_lib.o: cpp_lib.cpp
g++ -c cpp_lib.cpp -o cpp_lib.o
clean:
rm -rf c_main c_main.o cpp_lib.o
.PHONY: clean
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.34.244.41
※ 編輯: carylorrk 來自: 1.34.244.41 (01/12 15:57)
推
01/12 15:56, , 1F
01/12 15:56, 1F
→
01/12 15:57, , 2F
01/12 15:57, 2F
...居然是這麼簡單的問題 我蠢了 orz
感謝大大浪費時間推文XD||
不過用 gcc 來 link 會有什麼問題嗎?
※ 編輯: carylorrk 來自: 1.34.244.41 (01/12 16:03)
→
01/12 16:03, , 3F
01/12 16:03, 3F
→
01/12 16:04, , 4F
01/12 16:04, 4F
我知道 g++ 會自己連 libstdc++
會想用 gcc 來 link 主要是因為
正在開發的 project 是用 C(而且不能用 c++ compiler)
我自己加的小部分則是 C++
不想改變太多原本的 Makefile
我再看看怎麼樣比較好, 再次感謝大大囉!
→
01/12 16:05, , 5F
01/12 16:05, 5F
※ 編輯: carylorrk 來自: 1.34.244.41 (01/12 16:12)
→
01/12 17:51, , 6F
01/12 17:51, 6F