免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1565 | 回复: 3
打印 上一主题 下一主题

[C++] 请教c++程序与c程序链接的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-05-17 19:31 |只看该作者 |倒序浏览
各位大虾,小弟的程序是用c++写的,现在要调用一个用c编写的程序模块。c程序模块是作为一个静态库调用的,名字为libmodule.a

,在当前目录下。在我的c++代码中,如果加入#include <iostream>或者#include <iostream>等流操作头文件,程序链接的时候就

会出错;其他加入#include <string>等stl头文件,程序运行正常。

我的c++代码和Makefile如下:
我的c++文件仅为一个main.cpp文件,用来测试是否能够正常链接。

  1. // main.cpp

  2. #ifdef __cplusplus
  3. extern "C"
  4. {
  5. #endif
  6.     #include "header_file_of_c_module.h" /* header_file_of_c_module.h is one of the header files of the c module */
  7. #ifdef __cplusplus
  8. }
  9. #endif

  10. #include <string>

  11. int main(int argc, char * argv[])
  12. {
  13.     string str;
  14.     str = fun_of_c_module();
  15.     return 0;
  16. }
复制代码


  1. #Makefile

  2. CC= g++
  3. CPPFLAGS = -g -Wall
  4. OBJS = main.o

  5. exe: $(OBJS)
  6.         $(CC) $(CPPFLAGS) -o exe  $(OBJS) -lmodule -L.

  7. %.o: %.cpp
  8.         $(CC) $(CPPFLAGS) -c $< -o $@

  9. clean:
  10.                 rm -f $(OBJS) exe

复制代码

论坛徽章:
0
2 [报告]
发表于 2007-05-17 19:44 |只看该作者
using namespace std;

论坛徽章:
0
3 [报告]
发表于 2007-05-18 08:44 |只看该作者
呵呵,谢谢楼上兄弟。
看来是我没有说太清楚。现在的这个代码是可以用的。我可以把声明改成下面这个:

  1. std::string str;
复制代码


我的问题是,当在main.cpp文件中加入,
  1. #include <iostream>
复制代码

时,程序编译时就会出错
如果不加这个头文件,就没事了。

论坛徽章:
0
4 [报告]
发表于 2007-05-18 08:59 |只看该作者
问题解决了,但不知道原因是什么。
在我的main.cpp文件中,如果头文件的引入顺序为:

  1. // main.cpp

  2. #ifdef __cplusplus
  3. extern "C"
  4. {
  5. #endif
  6.     #include "header_file_of_c_module.h" /* header_file_of_c_module.h is one of the header files of the c module */
  7. #ifdef __cplusplus
  8. }
  9. #endif

  10. #include <string>
  11. [color=Red]#include  <iostream>[/color]
复制代码

则编译的时候会出错,如果是下面的顺序,就会正常编译


  1. //main.cpp

  2. [color=Red]#include <iostream>[/color]
  3. #ifdef __cplusplus
  4. extern "C"
  5. {
  6. #endif
  7.     #include "header_file_of_c_module.h" /* header_file_of_c_module.h is one of the header files of the c module */
  8. #ifdef __cplusplus
  9. }
  10. #endif

  11. #include <string>
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP