How to get object file to link first?

I’m trying to compile a Windows DLL for code originally intended for a Unix platform. One problem I have is that Windows fopen() defaults to O_TEXT, but Unix defaults to O_BINARY.

Windows recommends two ways to solve this:

  1. Use _set_fmode() function, didn’t work for me probably because I could not call it from correct context.
  2. Link with binmode.obj object file. This file is included with the compiler, and the compiler knows where to look for it.

The latter worked for my own code, but it does not seem to work for third party static libraries. Looking at the linker output, I can see that static libraries are included before binmode.obj, but binmode.obj was included before my own object files.

The real solution should be to persuade all external libraries to include binmode.obj, but this is somewhat non-trivial and might incur significant maintenance overhead in the future.

So I’d like to try to move the binmode.obj to the beginning of the linker command line, but this proved to be surprisingly difficult. I’ve tried:

  1. target_link_libraries( mylib PRIVATE binmode.obj ) - Got correct position, but got renamed to binmode.obj.lib.
  2. Tried making a static library with binmode.obj as a pre-compiled object, but got an error that the file has a relative path. I have no idea how to make it a full path.
  3. Tried adding it as a linker flag in different ways, even including using toolchain file, but it all ended up with binmode.obj being placed after libraries.

I’m now out of ideas and feel I need help with this. Any suggestions how to fix this?

What if you do target_sources(mylib PRIVATE binmode.obj)?

That would require a full path to binmode.obj. However, if I did an UNKNOWN IMPORTED GLOBAL library. I then used IMPORTED_LOCATION property set binmode.obj. This worked like a charm. Just a shame it didn’t solve my original problem, but that has nothing to do with CMake…

Ah, binmode.obj is provided by the platform and not your project? I don’t know if there’s a way to control the link line order. @brad.king?

Try using target_link_options(mylib PRIVATE binmode.obj).

Or, to apply to all shared library targets, put it in CMAKE_SHARED_LINKER_FLAGS.