Visual Studio 2012: exclude compiled file from lin

2019-07-22 11:57发布

问题:

I have a simple C language project with a few files being compiled. These are compiled to .obj files and then linked together. So far so good, now I need to exclude one of these files from linking.

I know this is quite unusual but this is exactly what I need: to compile a file but not link it to the project's output file. Using Visual Studio 2012.

I have no idea where the linker grabs the files to link although I've been looking to various places in project properties and the vcxproj file. It must be the compiler that passes the list of the compiled files. Is it possible to customize this building phase?

In Visual Studio 2010, it was easy to exclude a file from linking: By default, all the compiled files were stored as $(IntDir)%(FileName).obj. If an .obj file was stored elsewhere (in my case it is just %(FileName).obj), it was not linked. VS2012 seem to link all files actually compiled, regardless of their location.

If I change the file name to %(FileName).obj.x, nothing changes, the linker still links it.

I know I could compile the file as a Post-Build Event but I'd like to have the file compiled as a part of the standard building process.

回答1:

Let me answer my own question. There are three solutions to this problem:

  1. Post-Build Event compiles the file. This way, Visual Studio knows nothing about the file; many advantages of building it the standard way are lost.

  2. As @HansPassant suggested, separate project compiles the file. This doesn't prevent the linking step so unnecessary file is generated and the build is a bit slower. And in my case, moving the file to another project is questionable as it naturally belongs to the original project.

  3. I use the Pre-Link Event that I overlooked at first. I rewrite the compiled file with an empty one that is linked instead. It's a bit tricky but acceptable for me.