Compiling c++ program with additional libraries using Linux g++

雨燕双飞 提交于 2019-12-25 03:07:49

问题


I have created a program using visual studio 2010, which is error free. However, when I try running it in Linux, using the g++ compiler, I run into some error regarding unknown functions, that should be known.

I have the following files:

main.cpp
header.h
header.cpp   (all in the same folder)

header2.h (which is in a different folder, /.../header2

various libraries, stored in yet another folder, /.../libs

To compile the code I use the g++ compiler, writing the following in the terminal:

g++ main.cpp header.cpp -I/.../header2 -L/.../libs

I've read that the -I prefix specifies an include directory, with header files, while the -L prefix specifies libraries directories.

When I compile the program it gives me error, not recognizing functions from the time.h library. I checked if the header was installed, using find /usr/include -name time.h and it returned me the location of the time.h headers. I've also tried to compile with the -lrt, however it didn't work g++ main.cpp header.cpp -I/.../header2 -L/.../libs -lrt

I'm very new to linux, so any help would be appreciated.

Thanks.

edit: The actual error I'm getting is:

ellipse_fit.cpp: In function ‘void Create_Permutation(int*, int, int)’:
ellipse_fit.cpp:53:29: error: ‘rand’ was not declared in this scope
    a[i] = (int)((double)rand()/RAND_MAX*(double)range);

ellipse_fit.cpp:53:31: error: ‘RAND_MAX’ was not declared in this scope
    a[i] = (int)((double)rand()/RAND_MAX*(double)range);

The ellipse_fit.cpp would be the equivelent of the header.cpp I've mentioned in my example.


回答1:


This sort of thing happens when #include "something.h" in one system includes the header that you are relying on in your code, and when you move to another target system, "something.h" doesn't include that particular header (Windows sources also has a really annoying habit of including "stdafx.h", which in turn includes a few headerfiles that you didn't think about).

The solution is to include the header file that provides the function you need in your source files. Assuming headers are correctly using include guards, nothing bad will happen if you include the same file a few extra times. Even fairly complex header files take next to no time (I did an experiment as a result of a question here, showing that it added milliseconds to several seconds of compilation when you "unnecessarily" include a fairly large header file in 30 source files - modern compilers even cache header files, so if you include the same one twice, it knows it's seen that one and knows whether it contains include guards or not, and if it needs to take it in again or not, without even reading the file).



来源:https://stackoverflow.com/questions/22184899/compiling-c-program-with-additional-libraries-using-linux-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!