又他妈的一个上午浪费到这样一个无意义的事情中了。fuck!
需求:我需要将别人的vs工程导入到自建的工程文件中,就是已经获取了别人的vs工程的源码,要把它当做一个静态库使用。
这个问题,可能太简单,以至于网上在这里语焉不详。本人是使用vs的小白,今天才开始用,且是情非得已。平时,用这么大的ide,有必要吗。
这个问题可以转换为另一个等同的需求,自建一个库,怎么导入到主工程里?
第一步,创建一个静态库。名字叫common。按照[1]的操作来,先创建一个空工程,右击property->General,修改Configuration Type为lib。如图:
common里创建两个示例文件。使用一个宏定义,可以在Property->C/C++->Preprocessor
中增加一个CONDITION_1。
common.h
#ifndef _COMMON_H_
#define _COMMON_H_
#include<string>
namespace zsy{
class Shit{
public:
void Print(std::string name);
};
}
#endif
#include "common.h"
#include <iostream>
using namespace std;
namespace zsy {
void Shit::Print(std::string name){
#if defined CONDITION_1
std::cout <<"condition_1 " <<name << std::endl;
#else
std::cout << "condition_2 " << name << std::endl;
#endif
}
}
第二步,另创建一个工程,名字叫example。File->New->Project->Templates->Visual C++->Empty Project
. 增加一个test.cc的源文件。
test.cc
#include<iostream>
#include<string>
#include<string.h>
#include "common.h"
using namespace std;
using namespace zsy;
int main() {
std::string name = std::string("hello world!");
Shit shit;
shit.Print(name);
getchar();
return 0;
}
将common工程增加到主工程里。File->Add->Existing Project
,把common.vcxproj导入。但是此时,test.cc中引入的common.h文件标红,没有找到,需要添加include路径。可以在Include Directories中添加,如图。
要是这个时候build solution,会有一堆unresolved symbols的警告,common库中的函数没有编译进出,需要添加reference。右击example工程,‘add->reference’,选择common。
但是这个绝对路径配置,不利于工程的转移。可以采用相对路径../../common/common/
增加最终文件输出路径。
最终的代码下载[2]
[1]vs下制作和使用.lib静态库
[2]vs static lib https://github.com/SoonyangZhang/visual-studio-example