How to tell whether an executable was compiled for the present machine?

孤者浪人 提交于 2020-01-30 06:45:13

问题


I have some c code that I compile and run, in a directory that is accessible from many different unix computers (various linux and mac, occasionally others), with different OS's obviously needing different executables.

I have a simple shell script that invokes the appropriate executable, prog.$OSTYPE.$MACHTYPE, compiling it first if necessary. This is very simple (although it requires using csh in order to have $OSTYPE and $MACHTYPE be reliably defined) and it almost works.

However, it turns out that even $OSTYPE and $MACHTYPE are not enough: for example, compiling on OSX 10.5 yields an executable prog.darwin.i386 which, when invoked on OSX 10.4, crashes instantly.

Yes, recompiling every time I want to run the program is one way to solve this, but it seems excessive. I know having a bin directory on every machine is a standard solution, but a non-root user may not have much write access outside their home directory (which is common to all the machines).

So my question is, is there a better approach? The compiler (often gcc) obviously knows what kind of system it is compiling for -- is there a good portable way to find out what "kind of system" my script is running on, so it can invoke the correct executable, instead of one with undefined behavior?


回答1:


You could use gcc -v to figure out what the installed/runnable gcc thinks is the target arch for hosted compiling (something like $(gcc -v 2>&1 | grep Target: | sed 's/.*: *//') in bash)

edit

If you really want to be able to do this without having anything in particular installed, you could extract the config.guess script from gcc (its in the top level directory of any gcc source package) and run that. Unfortunately this won't work for all systems and might not exactly match what the system gcc package uses for some distributions, but this is the script used to configure gcc for building unless you explicitly override it...




回答2:


try to use file command from shell prompt




回答3:


Download some open source packages written in C and have a look at the file ./configure which is basically a large shell script that collects info from many sources, often by compiling and running short C programs. This will tell you everything that you need to know.

Since you are dealing with recent Mac OS X make sure you choose a package that is currently being maintained and supports OS X versions.



来源:https://stackoverflow.com/questions/5656257/how-to-tell-whether-an-executable-was-compiled-for-the-present-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!