[转]Linux / Windows 跨平台C++编程问题研究

April 3rd, 2008 by Sensheng Xu

最近由于工作需要而在跨平台C++编程上下了不少功夫,同时也因为经验太少而走了很多弯路。在这里稍微总结一下。 (注:这里的Windows标准指的是WinSDK,Linux标准指的是libc。)

一、关于线程同步

Linux下有pthread,当然,有人把它移植到了Windows,但是实现的方法其实是天壤之别。首先Linux下信号量是静态初始化的,因 此和Windows创建内核对象来初始化信号量的方式相比,效率要强得多。在移植Alex的Linux代码的过程中我们发现,在一段需要反复创建和销毁 semaphore的代码中,Windows XP的效率要比Linux (Ubuntu Server 7.10) 低上一小截,而Vista下则出现了明显的差距。为了在Linux和Windows维护同一份代码,最后我们不得不改设计,让Linux“迁就 ”Windows一把—-不再反复创建线程,而是一开始就创建一条线程死循环并从队列里拿数据。实验证明,这种方法使得程序在Linux和Windows 下效率都很高。结论:如果一开始就打算让你的程序L/W两边跑的话就好好想想semaphore/mutex/event的问题了。

二、关于许许多多的标准库函数

VC到目前的8.0是越来越远离标准了,M$不断的逼我们一步一步的远离标准库。大量的标准库函数会给出安全警告,并在名字前面加了下划线。 同时,M$“建议”我们使用_s的安全版本(例如itoa的安全版本是_itoa_s)。
有些标准函数的形参及返回值,Windows和Linux规定有所不同,这一点需要特别注意。其实这还不是最可怕的事情。有些是比较阴险的问题,一不小心 就会阴沟里翻船。例如,重载的bool operator() (…) const函数,M$所需要的比较结果和Linux正好相反。

三、关于并不标准的标准模板库STL

STL的hash_map给我们带来了很大的困扰。事实上STL的标准就已经有好几套。我甚至怀疑我们自己用C写一个hash_map的时间成本更小。其实从一开始移植的时候我就已经有不祥的预感,因为打开MSDN查看hash_map的文档就看到了这一句话:

In Visual C++ .NET 2003, members of the <hash_map> and <hash_set> header files are no longer in the std namespace, but rather have been moved into the stdext namespace. See The stdext Namespace for more information.

总结:使用标准库仍然不失是跨平台程序的法宝,但是要注意函数声明及返回值,必要时使用条件编译。C的移植性比C++好N多;STL是使用的时候很爽但移植的时候令人很痛苦,不推荐。

还在进一步努力中,不过问题已经一一得到解决。同时,希望可以和有这方面经验的朋友共同探讨一下这方面的问题,互相增进。

转自:没有一个名字但是有一个blog

This entry was posted in Linux. Bookmark the permalink.

7 Responses to [转]Linux / Windows 跨平台C++编程问题研究

  1. Academiannut says:

    Get ff14 gil and ffxiv cd key to prepare for the Final Fantasy XIV

  2. J.C.Amos says:

    Get FFXIV Gil and ffxiv cd key to prepare for the Final Fantasy XIV

  3. Rei Hino says:

    Get ff14 gil and ff14 cd key to prepare for the Final Fantasy XIV

  4. Defoe says:

    although i am spammer, we have cheap wow account and wow gold

  5. Thanks for taking the time to write that, I found it very detailed. If you get a chance you should visit my blog as well. I hope you have a great day!

  6. Thanks for taking the time to write that, I found it very interesting. If you get a chance you should visit my blog as well. I hope you have a good day!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment moderation is enabled. Your comment may take some time to appear.

Powered by WP Hashcash