首页 > 解决方案 > 链接库还是将它们带到 test.c 代码所在的本地目录更好?

问题描述

我正在努力理解 c 中的链接过程。(我是 C 新手)当我在本地目录(plplotExample.c 和 mathglExample)中将对象作为测试代码时,有些人抱怨标题不存在,即使我在 usr/local/.... 中有它们,除了 mathglExample . 测试代码如下:

plotExample.c

 #include "plConfig.h"
 #include "plcdemos.h"
 #define NSIZE    101

 int
 main( int argc, char *argv[] )
{
PLFLT x[NSIZE], y[NSIZE];
PLFLT xmin = 0., xmax = 1., ymin = 0., ymax = 100.;
int   i;

// Prepare data to be plotted.
for ( i = 0; i < NSIZE; i++ )
{
    x[i] = (PLFLT) ( i ) / (PLFLT) ( NSIZE - 1 );
    y[i] = ymax * x[i] * x[i];
}

// Parse and process command line arguments
plparseopts( &argc, argv, PL_PARSE_FULL );

// Initialize plplot
plinit();

// Create a labelled box to hold the plot.
plenv( xmin, xmax, ymin, ymax, 0, 0 );
pllab( "x", "y=100 x#u2#d", "Simple PLplot demo of a 2D line plot" );

// Plot the data that was prepared above.
plline( NSIZE, x, y );

// Close PLplot library
plend();

exit( 0 );
 }

错误信息是:

 plplotExample.c:2:10: fatal error: plConfig.h: No such file or directory

mathglExample.c

 #include <mgl2/mgl_cf.h>
 int main()
 {
 HMGL gr = mgl_create_graph(600,400);
 mgl_fplot(gr,"sin(pi*x)","","");
 mgl_write_frame(gr,"test.png","");
 mgl_delete_graph(gr);
 }

错误信息是

 In file included from /usr/include/mgl2/mgl_cf.h:29:0,
             from mathglExample.c:1:
          /usr/include/mgl2/data_cf.h:513:17: error: expected ‘,’ or ‘;’ before ‘mgl_find_roots’

如何修复链接或者我应该将所有代码和库放在一个目录下?我正在使用 linux opensuse jump 15.2 和 Geany 作为 c 编辑器。

标签: cmatplotliblinkershared-librariesplplot

解决方案


  1. plConfig.h必须与plotExample.c.
  2. 在文件/usr/include/mgl2/data_cf.h中,第 513 行,第 17 列,编译器需要一个“,”或“;” 前mgl_find_roots

如前所述,包含不是链接。在情况 1 中,您有一个文件未找到错误,在情况 2 中,源代码中有一个错误。

  1. 阅读有关如何包含头文件的信息:源文件包含(或者由于您使用的是 linux 和 geany,因此编译器可能是 gcc:GNU CPP Header Files
  2. 尝试阅读并理解编译器消息。

附录(根据您的评论)

-I plplot是一个相对目录。这意味着,编译器正在您当前的工作目录中搜索名为plplot. 使用编译器选项-I /usr/include/plplot或在源文件中使用以下包含(没有-I编译器选项):

#include <plplot/the_relevant_header_file.h>

据我了解,“pl ...”标头是第三方库(您的项目所依赖的)的一部分,并且例如由系统安装或制作,在任何一种情况下,都不要选择随机标头(从中项目)并重新定位它们并尝试从该目录中包含它们。因为,标头本身可能(可能)包含该库中的其他标头。在这种情况下,请使用 -I 选项(不推荐)或避免编译器选项(推荐)并从系统路径中包含,如我上面的示例中所述。这样做的原因是,从您的包含指令 (#include <plplot/...>) 中,您可以看到您(不仅是您,而且最重要的是其他人)从哪个库中包含符号。


推荐阅读