gcc 强大的编译器就不作介绍了

linux下用gcc命令编译多线程C程序文件和含有MySql数据库操作文件

1.编译多线程文件
gcc -o mylti_thread.o multi_thread.c -lpthread

其中的multi_thread.c表示源文件,mylti_thread.o表示编译产生的目标文件,-lpthread表示引入多线程库,在《Using the GNU Compiler Collection》gcc 4.30 中关于-lpthread的描述如下:
-lpthread      Add support for multithreading using the POSIX threads library. This option sets flags for both the preprocessor and linker. It does not affect the thread safety of object code produced by the compiler or that of libraries supplied with it. These are HP-UX specific flags. 要不然会出现类似以下错误

/tmp/cc20DpmC.o: In function `main':
multi_thread.c:(.text+0x78): undefined reference to `pthread_create'
multi_thread.c:(.text+0xe2): undefined reference to `pthread_create'
multi_thread.c:(.text+0xf6): undefined reference to `pthread_join'
multi_thread.c:(.text+0x10a): undefined reference to `pthread_join'

2.编译MySql数据库操作文件

gcc -o sqltest.o sqltest.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
或者gcc -o sqltest $(mysql_config --cflags) sqltest.c $(mysql_config --libs)
   参见网址 http://blog.163.com/zhangjinqing1234@126/blog/static/30730260200992251411161/
其中的sqltest.c表示源文件,sqltest.o表示编译产生的目标文件,-I表示指定头文件的默认搜索路径,-L表示指定要链接的库,同上面-l,具体可参见网址
http://blog.csdn.net/zhulinfeiba/archive/2009/08/20/4464727.aspx
-I后面的参数/usr/include/mysql可能会因为MySql安装的路径不同而有所改变,在终端输入:whereis mysql,结果如下:
mysql: /usr/bin/mysql /etc/mysql /usr/lib/mysql /usr/include/mysql /usr/share/mysql /usr/share/man/man1/mysql.1.gz
cd /usr/include/mysql ,然后 ls
decimal.h       my_dir.h         mysqld_error.h   sql_common.h
errmsg.h        my_getopt.h      mysql_embed.h    sql_state.h
keycache.h      my_global.h      mysql.h           sslopt-case.h
m_ctype.h       my_list.h        mysql_time.h     sslopt-longopts.h
m_string.h      my_net.h         mysql_version.h  sslopt-vars.h
my_alloc.h      my_no_pthread.h  my_sys.h         typelib.h
my_attribute.h  my_pthread.h     my_xml.h
my_config.h     mysql_com.h      ndb
my_dbug.h       mysqld_ername.h  raid.h
可以看见mysql.h在其中,在程序中已经#include "/usr/include/mysql/mysql.h"
如果没有 -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient会提示类似以下错误:

/tmp/ccc3sCuU.o: In function `main':
sqltest.c:(.text+0x11): undefined reference to `mysql_init'
sqltest.c:(.text+0x55): undefined reference to `mysql_real_connect'
sqltest.c:(.text+0x65): undefined reference to `mysql_error'
sqltest.c:(.text+0x95): undefined reference to `mysql_close'
collect2: ld returned 1 exit status

如果想省去以上麻烦,可以自己些makefile,正在学习中……

Logo

更多推荐