请教能否将c编译后的目标文件和C++的目标文件连接成可执行程序
请问能否将c编译后的目标文件和C++的目标文件连接成可执行程序?
如题所讲,其中c的目标文件使用gcc编译的,C++的目标文件使用g++编译的,我想将这两个目标文件连接可执行程序,可行吗?谢谢!
------解决方案--------------------
可以
不过要注意符号
C++使用c的部分的函数需要用extern "C "
------解决方案--------------------
In much cases,you can ,but in special cases,you will make faults.
////////////////////////////////////////////
//This is right:(Compile it like is g++ m.cpp -o m -lpthread)
#include <iostream>
#include <string>
using namespace std;
extern "C "
{
#include <pthread.h>
}
void*print(void*message)
{
char*msg=(char*)message;
for(int i=0;i <5;i++)
{
cout < <msg < <endl;
sleep(1);
}
}
class Thread
{
pthread_t th;
public:
Thread(string name)
{
pthread_create(&th,0,print,(void*)name.c_str());
pthread_join(th,0);
}
};
int main()
{
Thread th( "first ");
Thread th( "second ");
return 0;
}
////////////////////////////////////////////////////////////////
//This is wrong:
#include <iostream>
#include <string>
using namespace std;
extern "C "
{
#include <pthread.h>
}
class Thread
{
pthread_t th;
public:
Thread(string name)
{
pthread_create(&th,0,print,(void*)name.c_str());
pthread_join(th,0);
}
void*print(void*message)
{
char*msg=(char*)message;
for(int i=0;i <5;i++)
{
cout < <msg < <endl;
sleep(1);
}
}
};
int main()
{
Thread th1( "first ");
Thread th2( "second ");
return 0;
}
如题所讲,其中c的目标文件使用gcc编译的,C++的目标文件使用g++编译的,我想将这两个目标文件连接可执行程序,可行吗?谢谢!
------解决方案--------------------
可以
不过要注意符号
C++使用c的部分的函数需要用extern "C "
------解决方案--------------------
In much cases,you can ,but in special cases,you will make faults.
////////////////////////////////////////////
//This is right:(Compile it like is g++ m.cpp -o m -lpthread)
#include <iostream>
#include <string>
using namespace std;
extern "C "
{
#include <pthread.h>
}
void*print(void*message)
{
char*msg=(char*)message;
for(int i=0;i <5;i++)
{
cout < <msg < <endl;
sleep(1);
}
}
class Thread
{
pthread_t th;
public:
Thread(string name)
{
pthread_create(&th,0,print,(void*)name.c_str());
pthread_join(th,0);
}
};
int main()
{
Thread th( "first ");
Thread th( "second ");
return 0;
}
////////////////////////////////////////////////////////////////
//This is wrong:
#include <iostream>
#include <string>
using namespace std;
extern "C "
{
#include <pthread.h>
}
class Thread
{
pthread_t th;
public:
Thread(string name)
{
pthread_create(&th,0,print,(void*)name.c_str());
pthread_join(th,0);
}
void*print(void*message)
{
char*msg=(char*)message;
for(int i=0;i <5;i++)
{
cout < <msg < <endl;
sleep(1);
}
}
};
int main()
{
Thread th1( "first ");
Thread th2( "second ");
return 0;
}