【发布时间】:2015-04-07 17:45:25
【问题描述】:
我正在做一个项目,其中一些人已经用 C++ 编写了代码,我们必须在我们的 C 代码中使用它。所以我尝试了以下测试来编写一个演示相同的测试程序:
头文件为:
#ifndef h_files_n
#define h_files_n
#include<iostream>
#ifdef __cplusplus
extern "C" {
#endif
void add_func(int, int);
#ifdef __cplusplus
}
#endif
#endif
cpp 文件是:
#include"h_files.h"
void add_func(int num, int nums)
{
std :: cout << "The addition of numbers is : "<< num+nums << std endl;
}
c文件是:
#include<stdio.h>
#include"h_files.h"
int main()
{
printf("We are calling the C function form C++ file.\n");
add_func(10,15);
return 0;
}
makefile 是:
CC = gcc
inc = -I include
vpath %.c src
vpath %.cpp src
vpath %.o obj
all : $(addprefix obj/,functions.o main.o) run
run : main.o functions.o
$(CC) -o bin/$@ $^
obj/%.o : %.cpp
$(CXX) -c $(inc) $^ -o $@ -libstdc++
obj/%.o : %.c
$(CC) -c $(inc) $^ -o $@
.PHONY : clean
clean :
-rm -f obj/* bin/*
我收到以下错误:
g++ -c -I include src/functions.cpp -o obj/functions.o
gcc -c -I include src/main.c -o obj/main.o
gcc -o bin/run obj/main.o obj/functions.o
obj/functions.o: In function `add_func':
functions.cpp:(.text+0x1e): undefined reference to `std::cout'
functions.cpp:(.text+0x23): 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*)'
functions.cpp:(.text+0x2d): undefined reference to `std::ostream::operator<<(int)'
functions.cpp:(.text+0x32): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
functions.cpp:(.text+0x3a): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
obj/functions.o: In function `__static_initialization_and_destruction_0(int, int)':
functions.cpp:(.text+0x68): undefined reference to `std::ios_base::Init::Init()'
functions.cpp:(.text+0x77): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
make: *** [run] Error 1
- 如果我使用 g++ 作为链接器,那么它工作正常。但是 gcc 链接器给了我 问题。
- 我想到的问题是 g++ 修改的函数名和 gcc 不会破坏函数名称(符号)。
- 如果可能的话,是否有任何编译器标志可以避免名称修改。
- 避免使用 g++ 链接器的原因是它将链接视为 C++ 样式,但基本代码是 C 语言,因此可能会在调用代码时引入一些错误。
请有人提出解决方案。
【问题讨论】:
-
你不能在 C 程序中使用
cout。 -
我会尝试在链接阶段使用
g++:g++ -o bin/run obj/main.o obj/functions.o -
@Barmar 这不完全正确,这里没有问题。
-
@KhouriGiordano 对,但不感兴趣。带有函数定义的源文件被编译为 c++ 源代码。
-
您遇到过哪些实际错误(与
g++链接时)?你怕什么?