在.cpp文件中调用.c文件中的函数

时间:2025-03-22 12:44:07

问题描述:

提示:今日需要在c++项目中调用GMSSL中的SM2的相关函数接口。在包含头文件,链接动态库
.cpp中调用GMSSL(c语言库)的函数的代码:

@Override
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        
        /*从私钥证书里读取私钥*/
		EC_KEY *sm2_private_key = NULL;  //私钥
		char *passin = NULL;  //证书读取密码
		BIO *pri_in = NULL;  //输入输出流
		pri_in = BIO_new(BIO_S_FILE());
		
		if(BIO_read_filename(pri_in, "/home/pemfile/pri_key_pkcs8.pem") <= 0){
			cerr<<"Failed to read pem file"<<endl;
			return -1;
	}
		
		sm2_private_key = PEM_read_bio_ECPrivateKey(pri_in, NULL, NULL, passin);  //证书未设置密码,所以passin为NULL
		

编译命令:g++ -g -o parser_records.cpp --std=c++11 -I /usr/local/gmssl/include -lcrypto -ldl -pthread
在编译时已经把头文件包含进去,头文件路径给出(/usr/local/gmssl/include),把GM的动态库链接进去(-lcrypto)。在此情况下,编译时一直提示“函数PEM_read_bio_ECPrivateKey在此作用域中尚未申明”。

原因分析:

提示:后来发现是因为cpp文件中不能直接调用c的接口!


解决方案:

参照链接: /shaosunrise/article/details/81176880.

@Override

	extern "C" { 
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        #include <openssl/>
        }
        
        /*从私钥证书里读取私钥*/
		EC_KEY *sm2_private_key = NULL;  //私钥
		char *passin = NULL;  //证书读取密码
		BIO *pri_in = NULL;  //输入输出流
		pri_in = BIO_new(BIO_S_FILE());
		
		if(BIO_read_filename(pri_in, "/home/pemfile/pri_key_pkcs8.pem") <= 0){
			cerr<<"Failed to read pem file"<<endl;
			return -1;
	}
		
		sm2_private_key = PEM_read_bio_ECPrivateKey(pri_in, NULL, NULL, passin);  //证书未设置密码,所以passin为NULL
		

后编译通过。

相关文章