diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Makefile_many b/Makefile_many
index 19a525a..966a297 100644
--- a/Makefile_many
+++ b/Makefile_many
@@ -5,7 +5,7 @@
# C/CPP
# Don't use the standard names like `CC` and `CXX` to avoid `?=` getting overridden.
# by the Makefile default values.
-ALL_DEPEND ?=
+ALL_DEPEND ?=
MYCC ?= gcc
MYCXX ?= g++
G ?= gdb3
diff --git a/c-from-cpp/Makefile b/c-from-cpp/Makefile
index 744262a..2d528dd 100644
--- a/c-from-cpp/Makefile
+++ b/c-from-cpp/Makefile
@@ -5,10 +5,10 @@ main.out: main.o c.o
g++ -o '$@' $^
c.o: c.c
- gcc -c -o '$@' -std=c89 -Wextra -pedantic-errors '$<'
+ gcc -c -g -o '$@' -std=c89 -Wall -Wextra -pedantic-errors '$<'
main.o: main.cpp
- g++ -c -o '$@' -std=c++98 -Wextra -pedantic-errors '$<'
+ g++ -c -g -o '$@' -std=c++98 -Wall -Wextra -pedantic-errors '$<'
run: main.out
./main.out
diff --git a/c-from-cpp/README.md b/c-from-cpp/README.md
index 466229a..d6f1448 100644
--- a/c-from-cpp/README.md
+++ b/c-from-cpp/README.md
@@ -1,20 +1,3 @@
# C from C++
-How to call C code from C++.
-
-I urge you to use `readelf -s` on the object files to see what they contain.
-
-Note that the symbols defined by the C++ compiler (thus when using `g++` instead of `gcc`) are much more complicated than those generated by the C compiler.
-
-This is probably the case because C++ has features like templates and classes, so it must add prefixes and suffixes in an specific manner to make the symbols unique.
-
-Therefore, it is much easier to call `c` from `c++` (with a C++ compiler) rather than call `c++` from `c` (with a C compiler). Of course, this is because `c++` was made to be backwards compatible with `c`.
-
-See how `g++` links by default to the `c` standard libraries (for backwards compatibility) since you can simply call functions like `printf` without linking.
-
-## extern "C"
-
-`g++` compiles:
-
-- defined functions to use plain C names in the objects instead of the mangled ones
-- undefined declared functions to depend on the C name instead of the mangled one
+
diff --git a/c-from-cpp/c.h b/c-from-cpp/c.h
index 17beebe..f8a5287 100644
--- a/c-from-cpp/c.h
+++ b/c-from-cpp/c.h
@@ -1,9 +1,8 @@
#ifndef C_H
#define C_H
+/* This ifdef allows the header to be used from both C and C++. */
#ifdef __cplusplus
-// This is required otherwise he C++ includer will look
-// for the undefined mangled name.
extern "C" {
#endif
int f();
diff --git a/c-from-cpp/main.cpp b/c-from-cpp/main.cpp
index 6cc3627..26dc7e6 100644
--- a/c-from-cpp/main.cpp
+++ b/c-from-cpp/main.cpp
@@ -4,5 +4,4 @@
int main() {
assert(f() == 1);
- return 0;
}
diff --git a/c/interactive/audio_gen.c b/c/interactive/audio_gen.c
index 2de63dc..f92ea51 100644
--- a/c/interactive/audio_gen.c
+++ b/c/interactive/audio_gen.c
@@ -32,7 +32,7 @@ double PI2;
void write_ampl(FILE *f, point_type ampl) {
uint8_t bytes[2];
bytes[0] = ampl >> 8;
- bytes[1] = ampl & 8;
+ bytes[1] = ampl & 0xFF;
fwrite(bytes, 2, sizeof(uint8_t), f);
}
diff --git a/c/string_to_int.c b/c/string_to_int.c
index 7f11ecc..b176e30 100644
--- a/c/string_to_int.c
+++ b/c/string_to_int.c
@@ -1,6 +1,4 @@
-/*
-http://stackoverflow.com/questions/7021725/converting-string-to-integer-c/12923949#12923949
-*/
+/* http://stackoverflow.com/questions/7021725/converting-string-to-integer-c/12923949#12923949 */
#include
#include
@@ -16,26 +14,25 @@ typedef enum {
STR2INT_INCONVERTIBLE
} str2int_errno;
-/*
-Convert string s to int out.
-
-@param[out] out The converted int. Cannot be NULL.
-
-@param[in] s Input string to be converted.
-
- The format is the same as strtol,
- except that the following are inconvertible:
-
- - empty string
- - leading whitespace
- - any trailing characters that are not part of the number
-
- Cannot be NULL.
-
-@param[in] base Base to interpret string in. Same range as strtol (2 to 36).
-
-@return Indicates if the operation succeeded, or why it failed.
-*/
+/* Convert string s to int out.
+ *
+ * @param[out] out The converted int. Cannot be NULL.
+ *
+ * @param[in] s Input string to be converted.
+ *
+ * The format is the same as strtol,
+ * except that the following are inconvertible:
+ *
+ * - empty string
+ * - leading whitespace
+ * - any trailing characters that are not part of the number
+ *
+ * Cannot be NULL.
+ *
+ * @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
+ *
+ * @return Indicates if the operation succeeded, or why it failed.
+ */
str2int_errno str2int(int *out, char *s, int base) {
char *end;
if (s[0] == '\0' || isspace(s[0]))
@@ -92,12 +89,11 @@ int main(void) {
assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);
- /*
- int overflow.
-
- `if` needed to avoid undefined behaviour
- on `INT_MAX + 1` if INT_MAX == LONG_MAX.
- */
+ /* int overflow.
+ *
+ * `if` needed to avoid undefined behaviour
+ * on `INT_MAX + 1` if INT_MAX == LONG_MAX.
+ */
if (INT_MAX < LONG_MAX) {
sprintf(s, "%ld", (long int)INT_MAX + 1L);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
diff --git a/cpp-from-c/Makefile b/cpp-from-c/Makefile
index 9ef5bd5..49af79a 100644
--- a/cpp-from-c/Makefile
+++ b/cpp-from-c/Makefile
@@ -5,10 +5,10 @@ main.out: main.o cpp.o
g++ -o '$@' $^
cpp.o: cpp.cpp
- g++ -c -o '$@' -pedantic-errors -std=c++98 -Wextra '$<'
+ g++ -c -g -o '$@' -pedantic-errors -std=c++98 -Wall -Wextra '$<'
main.o: main.c
- gcc -c -o '$@' -pedantic-errors -std=c89 -Wextra '$<'
+ gcc -c -g -o '$@' -pedantic-errors -std=c89 -Wall -Wextra '$<'
run: main.out
./main.out
diff --git a/cpp-from-c/README.md b/cpp-from-c/README.md
index 9f90e1f..205e7eb 100644
--- a/cpp-from-c/README.md
+++ b/cpp-from-c/README.md
@@ -1,13 +1,3 @@
-# C from C++
+# C++ from C
-How to call C code from C++.
-
-I urge you to use `readelf -s` on the object files to see what they contain.
-
-Note that the symbols defined by the C++ compiler (thus when using `g++` instead of `gcc`) are much more complicated than those generated by the C compiler.
-
-This is probably the case because C++ has features like templates and classes, so it must add prefixes and suffixes in an specific manner to make the symbols unique.
-
-Therefore, it is much easier to call `c` from `c++` (with a C++ compiler) rather than call `c++` from `c` (with a C compiler). Of course, this is because `c++` was made to be backwards compatible with `c`.
-
-See how `g++` links by default to the `c` standard libraries (for backwards compatibility) since you can simply call functions like `printf` without linking.
+
diff --git a/cpp-from-c/cpp.cpp b/cpp-from-c/cpp.cpp
index f425489..fded4e0 100644
--- a/cpp-from-c/cpp.cpp
+++ b/cpp-from-c/cpp.cpp
@@ -1,9 +1,17 @@
#include "cpp.h"
-int f() {
- return 1;
+int f(int i) {
+ return i + 1;
}
-class C {
- static int f() { return 1; }
-};
+int f(float i) {
+ return i + 2;
+}
+
+int f_int(int i) {
+ return f(i);
+}
+
+int f_float(float i) {
+ return f(i);
+}
diff --git a/cpp-from-c/cpp.h b/cpp-from-c/cpp.h
index 90c449c..2ab77b4 100644
--- a/cpp-from-c/cpp.h
+++ b/cpp-from-c/cpp.h
@@ -2,11 +2,13 @@
#define CPP_H
#ifdef __cplusplus
-// This is required otherwise C++ will compile to mangled names,
-// and the C includer will not find them.
+// C cannot see these overloaded prototypes, or else it would get confused.
+int f(int i);
+int f(float i);
extern "C" {
#endif
- int f();
+int f_int(int i);
+int f_float(float i);
#ifdef __cplusplus
}
#endif
diff --git a/cpp-from-c/main.c b/cpp-from-c/main.c
index b1b41ac..8f0fd0f 100644
--- a/cpp-from-c/main.c
+++ b/cpp-from-c/main.c
@@ -2,8 +2,8 @@
#include "cpp.h"
-int main() {
- assert(f() == 1);
- assert(f() == 1);
+int main(void) {
+ assert(f_int(1) == 2);
+ assert(f_float(1.0) == 3);
return 0;
}
diff --git a/cpp/README.md b/cpp/README.md
index 2fe0179..1aca54c 100644
--- a/cpp/README.md
+++ b/cpp/README.md
@@ -82,6 +82,7 @@
1. [atomic](atomic_bool.cpp.off)
1. [mutex](mutex.cpp)
1. [algorithm](algorithm.cpp)
+ 1. [heap](heap.cpp)
1. [functional](functional.cpp)
1. [iterator](iterator.cpp)
1. [limits](limits.cpp)
@@ -92,8 +93,13 @@
1. [tuple](tuple.cpp)
1. Smart pointers
1. [unique_ptr](unique_ptr.cpp)
- 1. [random](random.cpp)
1. [Interactive](interactive/)
+ 1. [bst_vs_heap](interactive/bst_vs_heap.cpp)
+ 1. [chrono](interactive/chrono.cpp)
+ 1. [random](interactive/random.cpp)
+ 1. thread
+ 1. [sleep_for](interactive/sleep_for.cpp)
+ 1. [thread_count](interactive/thread_count.cpp)
1. Applications
1. [Design patterns](design_patterns.cpp)
diff --git a/cpp/algorithm.cpp b/cpp/algorithm.cpp
index b4a94b4..fdc3957 100644
--- a/cpp/algorithm.cpp
+++ b/cpp/algorithm.cpp
@@ -1,7 +1,3 @@
-/*
-# algorithm
-*/
-
#include "common.hpp"
int main() {
@@ -25,22 +21,21 @@ int main() {
assert((v == std::vector{1, 0, 2}));
}
- /*
- # swap
-
- Does things equivalent to:
-
- template void swap (T& a, T& b)
- {
- T c(a); a=b; b=c;
- }
-
- However stdlib can specialize it to do operations more efficiently.
-
- Some stdlib classes implement swap as a method.
-
- Particularly important because of the copy and swap idiom.
- */
+ /* # swap
+ *
+ * Does things equivalent to:
+ *
+ * template void swap (T& a, T& b)
+ * {
+ * T c(a); a=b; b=c;
+ * }
+ *
+ * However stdlib can specialize it to do operations more efficiently.
+ *
+ * Some stdlib classes implement swap as a method.
+ *
+ * Particularly important because of the copy and swap idiom.
+ */
// # randomize
{
@@ -56,24 +51,22 @@ int main() {
assert(v2 == std::vector({3, 2, 0, 1, 3}));
}
- /*
- # equal
-
- Compares ranges of two containers.
- */
+ /* # equal
+ *
+ * Compares ranges of two containers.
+ */
{
std::vector v {0, 1, 2 };
std::vector v2{ 1, 2, 3};
assert(std::equal(v.begin() + 1, v.end(), v2.begin()));
}
- /*
- # accumulate
-
- Sum over range with operator+
-
- Also has functional versions http://www.cplusplus.com/reference/numeric/accumulate/
- */
+ /* # accumulate
+ *
+ * Sum over range with operator+
+ *
+ * Also has functional versions http://www.cplusplus.com/reference/numeric/accumulate/
+ */
{
{
std::vector v{2, 0, 1};
@@ -89,11 +82,10 @@ int main() {
}
}
- /*
- # find
-
- Return iterator to first found element.
- */
+ /* # find
+ *
+ * Return iterator to first found element.
+ */
{
std::vector v{2,0,1};
unsigned int pos;
@@ -111,29 +103,27 @@ int main() {
assert(pos == v.size());
}
- /*
- # find_if
-
- Like find, but using an arbitrary condition on each element instead of equality.
-
- Consider usage with C++11 lambdas and functional.
- */
+ /* # find_if
+ *
+ * Like find, but using an arbitrary condition on each element instead of equality.
+ *
+ * Consider usage with C++11 lambdas and functional.
+ */
{
std::vector v{2, 0, 1};
assert(std::find_if (v.begin(), v.end(), odd) == --v.end());
}
- /*
- # binary_search
-
- Container must be already sorted.
-
- Log complexity.
-
- Only states if the element is present or not, but does not get its position.
-
- If you want to get the position of those items, use `equal_range`, `lower_bound` or `upper_bound`.
- */
+ /* # binary_search
+ *
+ * Container must be already sorted.
+ *
+ * Log complexity.
+ *
+ * Only states if the element is present or not, but does not get its position.
+ *
+ * If you want to get the position of those items, use `equal_range`, `lower_bound` or `upper_bound`.
+ */
{
std::vector v{0, 1, 2};
@@ -142,37 +132,34 @@ int main() {
assert(std::binary_search(v.begin(), v.end() - 1, 2) == false);
}
- /*
- # lower_bound
-
- Finds first element in container which is not less than val.
- */
+ /* # lower_bound
+ *
+ * Finds first element in container which is not less than val.
+ */
{
std::vector v{0, 2, 3};
auto it = std::lower_bound(v.begin(), v.end(), 1);
assert(it - v.begin() == 1);
}
- /*
- # upper_bound
-
- Finds first element in container is greater than val.
- */
+ /* # upper_bound
+ *
+ * Finds first element in container is greater than val.
+ */
{
std::vector v{0, 1, 2};
auto it = std::upper_bound(v.begin(), v.end(), 1);
assert(it - v.begin() == 2);
}
- /*
- # equal_range
-
- Finds first and last location of a value iniside a ranged container.
-
- Return values are the same as lower_bound and upper_bound.
-
- log complexity.
- */
+ /* # equal_range
+ *
+ * Finds first and last location of a value iniside a ranged container.
+ *
+ * Return values are the same as lower_bound and upper_bound.
+ *
+ * log complexity.
+ */
{
std::vector v{0, 1, 1, 2};
std::vector::iterator begin, end;
@@ -197,20 +184,19 @@ int main() {
assert(*std::min_element(v.begin(), v.end()) == 0);
}
- /*
- # advance
-
- Advance iterator by given number.
-
- If random access, simply adds + N.
-
- Else, calls `++` N times.
-
- Advantage over `+`: only random access containers support `+`,
- but this works for any container, allowing one to write more general code.
-
- Beware however that this operation will be slow for non random access containers.
- */
+ /* # advance
+ *
+ * Advance iterator by given number.
+ *
+ * If random access, simply adds + N.
+ *
+ * Else, calls `++` N times.
+ *
+ * Advantage over `+`: only random access containers support `+`,
+ * but this works for any container, allowing one to write more general code.
+ *
+ * Beware however that this operation will be slow for non random access containers.
+ */
{
std::vector v{0, 1, 2};
auto it = v.begin();
@@ -219,11 +205,10 @@ int main() {
}
#if __cplusplus >= 201103L
- /*
- # next
-
- Same as advance, but returns a new iterator instead of modifying the old one.
- */
+ /* # next
+ *
+ * Same as advance, but returns a new iterator instead of modifying the old one.
+ */
{
std::vector v{0, 1, 2};
auto it(v.begin());
@@ -232,125 +217,4 @@ int main() {
assert(*itNext == 2);
}
#endif
-
- /*
- # priority queue
-
- Offers `O(1)` access to the smalles element.
-
- Other operatoins vary between `O(n)` and `O(1).
-
- Most common implementaions are via:
-
- - binary heap
- - fibonacci heap
-
- Boost offers explicit heap types: fibonacci, binary and others.
-
- But no guarantees are made.
-
- As of C++11, does not support the increase key operation.
-
- A binary heap without increase key can be implemented via the heap function family under algorithm.
- */
-
- /*
- # heap
-
- Binary heap implementation.
-
-
-
- In short:
-
- - getting largest element is O(1)
- - removing the largest element is O(lg) for all implementation
- - other operations (insertion) may be O(1) or O(lg) depending on the implementation.
-
- this makes for a good priority queue.
- Exact heap type is not guaranteed. As of 2013, it seems that most implementations use binary heaps.
-
- For specific heaps such as Fibonacci, consider [Boost](http://www.boost.org/doc/libs/1_49_0/doc/html/heap.html).
-
-
-
- There is no concrete heap data structure in C++:
- only heap operations over random access data structures.
- This is why this is under algoritms and is not a data structure of its own.
-
- There is however a `priority_queue` stdlib container.
-
- Why random access structure is needed:
- */
- {
- int myints[]{10, 20, 30, 5, 15};
- std::vector v(myints, myints + 5);
-
- /*
- # make_heap
-
- Make random access data structure into a heap.
-
- This changes the element order so that the range has heap properties
-
- Worst case time: $O(n)$.
- */
- std::make_heap(v.begin(), v.end());
- assert(v.front() == 30);
-
- /*
- # pop_heap
-
- Remove the largest element from the heap.
-
- That element is moved to the end of the data structure, but since the
- heap should have its length reduced by one, that element will then be out of the heap.
-
- Assumes that the input range is already a heap (made with `make_heap` for example).
- */
- std::pop_heap(v.begin(), v.end());
-
- //the element still exists on the data structure
- assert(v.back() == 30);
-
- //the second largest element hat become the largets
- assert(v.front() == 20);
-
- //remove the element from the data structure definitively
- v.pop_back();
-
- /*
- # push_heap
-
- Insert element into a heap.
-
- Assumes that:
-
- - the range 0 - (end - 1) was already a heap
- - the new element to be inserted into that heap is at end.
- */
-
- //add the new element to the data structure
- v.push_back(99);
-
- //reorganize the data so that the last element will be placed in the heap
- std::push_heap(v.begin(), v.end());
-
- assert(v.front() == 99);
-
- /*
- # sort_heap
-
- Assumes that the input range is a heap, and sorts it in increasing order.
-
- The assumption that we have a heap allows for $O(ln)$ sorting,
- much faster than the optimal bound $O(n log n)$.
-
- This is exactly what the heapsort alrotithm does: make_heap and then sort_heap.
- */
-
- std::sort_heap(v.begin(), v.end());
- //assert(v)
- //v == 5 10 15 20 99
- }
}
diff --git a/cpp/common.hpp b/cpp/common.hpp
index 72bbe64..8405996 100644
--- a/cpp/common.hpp
+++ b/cpp/common.hpp
@@ -28,6 +28,7 @@
#include
#include // partial sums, differences on std::vectors of numbers
#include // ostream
+#include // priority_queue
#include // ratio, nano
#include
#include // multiset, set
diff --git a/cpp/heap.cpp b/cpp/heap.cpp
new file mode 100644
index 0000000..716cd9f
--- /dev/null
+++ b/cpp/heap.cpp
@@ -0,0 +1,137 @@
+/* First learn how binary heaps work, and how they can efficiently implement
+ * Dijkstra more efficiently than BST:
+ * https://stackoverflow.com/questions/6147242/heap-vs-binary-search-tree-bst/29548834#29548834
+ *
+ * There are two ways to make priority queues in C++:
+ *
+ * - `make_heap` and other functions in the family, which implement a heap
+ * on top of a random access container, typically std::vector.
+ *
+ * - `priority_queue` class, which seems to just use `std::vector` + `make_heap` by default
+ * internally: https://stackoverflow.com/questions/11266360/when-should-i-use-make-heap-vs-priority-queue
+ */
+
+#include "common.hpp"
+
+int main() {
+ int myints[]{10, 20, 30, 5, 15};
+ std::vector v(myints, myints + 5);
+
+ // Heap functions.
+ {
+ /* # make_heap
+ *
+ * Make random access data structure into a heap.
+ */
+ {
+ std::make_heap(v.begin(), v.end());
+ assert(v.front() == 30);
+ }
+
+ /* # pop_heap
+ *
+ * Remove the largest element from the heap.
+ *
+ * That element is moved to the end of the data structure, but since the
+ * heap should have its length reduced by one, the element is effectively removed.
+ *
+ * Assumes that the input range is already a heap, made with `make_heap` for example.
+ */
+ {
+ std::pop_heap(v.begin(), v.end());
+
+ // The element still exists on the data structure.
+ assert(v.back() == 30);
+
+ // The second largest element hat become the largest.
+ assert(v.front() == 20);
+
+ // Remove the element from the data structure definitively
+ v.pop_back();
+ }
+
+ /* # push_heap
+ *
+ * Insert element into a heap.
+ *
+ * Assumes that:
+ *
+ * - the range 0 - (end - 1) was already a heap
+ * - the new element to be inserted into that heap is at end.
+ */
+ {
+ // Add the new element to the data structure.
+ v.push_back(99);
+
+ // Reorganize the data so that the last element will be placed in the heap.
+ std::push_heap(v.begin(), v.end());
+
+ assert(v.front() == 99);
+ }
+
+ /* # sort_heap
+ *
+ * Assumes that the input range is a heap, and sorts it in increasing order.
+ *
+ * The assumption that we have a heap allows for $O(ln)$ sorting,
+ * much faster than the optimal bound $O(n log n)$.
+ *
+ * This is exactly what the heapsort algorithm does: make_heap and then sort_heap.
+ */
+ {
+ std::sort_heap(v.begin(), v.end());
+ //assert(v)
+ //v == 5 10 15 20 99
+ }
+ }
+
+ /* # priority_queue
+ *
+ * It could however use some other implementation in theory, and it does seem that GCC libstdc++ does provide
+ * a few alternatives with the policy base
+ *
+ * No Fibonacci as of 7.3.0 however:
+ *
+ * - https://gcc.gnu.org/onlinedocs/gcc-7.3.0/libstdc++/manual/manual/policy_based_data_structures_test.html#performance.priority_queue
+ * - http://stackoverflow.com/questions/14118367/stl-for-fibonacci-heap
+ *
+ * TODO As of C++11, does not support the increase key operation.
+ *
+ * Boost offers explicit heap types: Fibonacci, binary and others.
+ */
+ {
+ // max
+ {
+ std::priority_queue q;
+ for(int n : {1,8,5,6,3,4,0,9,7,2})
+ q.push(n);
+ assert(q.top() == 9);
+ q.pop();
+ assert(q.top() == 8);
+ q.pop();
+ assert(q.top() == 7);
+ q.pop();
+ }
+
+ // min
+ {
+ std::priority_queue, std::greater> q;
+ for(int n : {1,8,5,6,3,4,0,9,7,2})
+ q.push(n);
+ assert(q.top() == 0);
+ q.pop();
+ assert(q.top() == 1);
+ q.pop();
+ assert(q.top() == 2);
+ q.pop();
+ }
+
+ // Dupes are accepted unlike in sets.
+ {
+ std::priority_queue, std::greater> q;
+ q.push(1);
+ q.push(1);
+ assert(q.size() == 2);
+ }
+ }
+}
diff --git a/cpp/interactive/.gitignore b/cpp/interactive/.gitignore
new file mode 100644
index 0000000..2084151
--- /dev/null
+++ b/cpp/interactive/.gitignore
@@ -0,0 +1,2 @@
+/bst_vs_heap.dat
+/bst_vs_heap.png
diff --git a/cpp/interactive/README.md b/cpp/interactive/README.md
deleted file mode 100644
index 31400e1..0000000
--- a/cpp/interactive/README.md
+++ /dev/null
@@ -1,4 +0,0 @@
-# Interactive
-
-1. [sleep_for](sleep_for.cpp)
-1. [chrono](chrono.cpp)
diff --git a/cpp/interactive/bst_vs_heap.cpp b/cpp/interactive/bst_vs_heap.cpp
new file mode 100644
index 0000000..68a0c76
--- /dev/null
+++ b/cpp/interactive/bst_vs_heap.cpp
@@ -0,0 +1,58 @@
+#include "common.hpp"
+
+int main(int argc, char **argv) {
+ typedef uint64_t I;
+ I *randoms;
+ size_t i, j, n, granule;
+ std::priority_queue heap;
+ std::set bst;
+ std::uniform_int_distribution dist;
+ std::random_device dev;
+ unsigned int seed = dev();
+ std::mt19937 prng(seed);
+
+ if (argc > 1) {
+ n = std::stoi(argv[1]);
+ } else {
+ n = 1000000;
+ }
+ if (argc > 2) {
+ granule = std::stoi(argv[2]);
+ } else {
+ granule = 10;
+ }
+ randoms = new I[granule];
+ for (i = 0; i < n / granule; ++i) {
+ for (j = 0; j < granule; ++j) {
+ randoms[j] = dist(prng);
+ }
+
+ // BST.
+ auto start = std::chrono::high_resolution_clock::now();
+ for (j = 0; j < granule; ++j) {
+ bst.insert(randoms[j]);
+ }
+ auto end = std::chrono::high_resolution_clock::now();
+ auto dt_bst = end - start;
+
+ // Heap.
+ start = std::chrono::high_resolution_clock::now();
+ for (j = 0; j < granule; ++j) {
+ heap.emplace(randoms[j]);
+ }
+ end = std::chrono::high_resolution_clock::now();
+ auto dt_heap = end - start;
+
+ // Output.
+ std::cout
+ << std::chrono::duration_cast(dt_heap).count() << " "
+ << std::chrono::duration_cast(dt_bst).count() << std::endl;
+ }
+ delete[] randoms;
+
+ // Sanity check.
+ for (auto it = bst.rbegin(); it != bst.rend(); ++it) {
+ assert(*it == heap.top());
+ heap.pop();
+ }
+}
diff --git a/cpp/interactive/bst_vs_heap.gnuplot b/cpp/interactive/bst_vs_heap.gnuplot
new file mode 100755
index 0000000..c8ee2ba
--- /dev/null
+++ b/cpp/interactive/bst_vs_heap.gnuplot
@@ -0,0 +1,10 @@
+#!/usr/bin/env gnuplot
+set terminal png size 1024, 1024
+set output "bst_vs_heap.png"
+set multiplot layout 2,1 title "Heap vs BST insert time"
+set xlabel "size"
+set ylabel "nanoseconds"
+set title "Heap"
+plot "bst_vs_heap.dat" using 2 notitle
+set title "BST"
+plot "bst_vs_heap.dat" using 3 notitle
diff --git a/cpp/interactive/chrono.cpp b/cpp/interactive/chrono.cpp
index 90d56db..ed1cee9 100644
--- a/cpp/interactive/chrono.cpp
+++ b/cpp/interactive/chrono.cpp
@@ -1,9 +1,6 @@
-/*
-# chrono
-
-What the clocks map to in GCC Linux:
-http://stackoverflow.com/questions/12392278/measure-time-in-linux-time-vs-clock-vs-getrusage-vs-clock-gettime-vs-gettimeof
-*/
+/* What the clocks map to in GCC Linux:
+ * http://stackoverflow.com/questions/12392278/measure-time-in-linux-time-vs-clock-vs-getrusage-vs-clock-gettime-vs-gettimeof
+ */
#include "common.hpp"
@@ -14,8 +11,10 @@ int main() {
std::cout << "steady_clock::period::den = " << std::chrono::steady_clock::period::den << std::endl;
std::cout << "system_clock::period::den = " << std::chrono::system_clock::period::den << std::endl;
- // high_resolution_clock
- // Wall clock: sleeps are counted.
+ /* # high_resolution_clock
+ *
+ * Wall clock: sleeps are counted.
+ */
{
std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
@@ -42,19 +41,18 @@ int main() {
std::cout << "system_clock after sleep = " << std::chrono::duration_cast(dt).count() << std::endl;
}
- /*
- # time_point
-
- Convertions to base types:
-
- - http://stackoverflow.com/questions/12835577/how-to-convert-stdchronotime-point-to-calendar-datetime-string-with-fraction
- - http://stackoverflow.com/questions/33785564/how-do-i-get-seconds-since-epoch-as-a-double-given-a-time-point
- - http://stackoverflow.com/questions/31255486/c-how-do-i-convert-a-stdchronotime-point-to-long-and-back
- */
+ /* # time_point
+ *
+ * Convertions to base types:
+ *
+ * - http://stackoverflow.com/questions/12835577/how-to-convert-stdchronotime-point-to-calendar-datetime-string-with-fraction
+ * - http://stackoverflow.com/questions/33785564/how-do-i-get-seconds-since-epoch-as-a-double-given-a-time-point
+ * - http://stackoverflow.com/questions/31255486/c-how-do-i-convert-a-stdchronotime-point-to-long-and-back
+ */
{
std::cout << "nanoseconds since system_clock epoch = " << std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() << std::endl;
std::cout << "nanoseconds since steady_clock epoch = " << std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count() << std::endl;
}
- return 0;
+ return 0;
#endif
}
diff --git a/cpp/interactive/random.cpp b/cpp/interactive/random.cpp
new file mode 100644
index 0000000..0b67caa
--- /dev/null
+++ b/cpp/interactive/random.cpp
@@ -0,0 +1,19 @@
+#include "common.hpp"
+
+int main() {
+ /* # random_device
+ *
+ * Ultimate C++11 method to seed a PRNG, wraps over `/dev/urandom`.
+ *
+ * http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand/13004555#13004555
+ */
+ {
+ std::random_device dev;
+ unsigned int seed = dev();
+ std::mt19937 prng(seed);
+ std::uniform_int_distribution<> dist(1, 10);
+ for (unsigned int i = 0; i < 10; ++i) {
+ std::cout << dist(prng) << std::endl;
+ }
+ }
+}
diff --git a/cpp/interactive/sleep_for.cpp b/cpp/interactive/sleep_for.cpp
index e08ada0..55fbff9 100644
--- a/cpp/interactive/sleep_for.cpp
+++ b/cpp/interactive/sleep_for.cpp
@@ -1,7 +1,3 @@
-/*
-# sleep_for
-*/
-
#include "common.hpp"
int main() {
diff --git a/cpp/interactive/thread_count.cpp b/cpp/interactive/thread_count.cpp
index e92c606..b1804c9 100644
--- a/cpp/interactive/thread_count.cpp
+++ b/cpp/interactive/thread_count.cpp
@@ -1,8 +1,7 @@
-/*
-Dummy operation that uses a lot of CPU, but very little memory.
-
-Used as a control for the parallel version, which should me scalably faster.
-*/
+/* Dummy operation that uses a lot of CPU, but very little memory.
+ *
+ * Used as a control for the parallel version, which should me scalably faster.
+ */
#include "common.hpp"
diff --git a/cpp/map.cpp b/cpp/map.cpp
index 28acb6f..7e793f1 100644
--- a/cpp/map.cpp
+++ b/cpp/map.cpp
@@ -1,24 +1,24 @@
/*
# map
- http://www.cplusplus.com/reference/map/map/
+http://www.cplusplus.com/reference/map/map/
- Also comes in an unordered version `unordered_map`.
+Also comes in an unordered version `unordered_map`.
- Ordered.
+Ordered.
- Also comes in an multiple value input version `multimap`.
+Also comes in an multiple value input version `multimap`.
- Does not require a hash function. Usually implemented as a self balancing tree such as a rb tree.
+Does not require a hash function. Usually implemented as a self balancing tree such as a rb tree.
# hashmap
- There seems to be no explicit hashmap container, only a generic map interface,
+There seems to be no explicit hashmap container, only a generic map interface,
- However unordered_map is likely to be hashmap based.
+However unordered_map is likely to be hashmap based.
- A nonstandard `hash_map` already provided with gcc and msvc++.
- It is placed in the `std::` namespace, but it is *not* ISO.
+A nonstandard `hash_map` already provided with gcc and msvc++.
+It is placed in the `std::` namespace, but it is *not* ISO.
*/
#include "common.hpp"
@@ -76,7 +76,7 @@ int main() {
}
/*
- emplace
+ # emplace
Put a value pair into the map without creating the pair explicitly.
diff --git a/cpp/no_base_no_member.hpp b/cpp/no_base_no_member.hpp
index e673e62..13897d6 100644
--- a/cpp/no_base_no_member.hpp
+++ b/cpp/no_base_no_member.hpp
@@ -56,7 +56,9 @@ class NoBaseNoMember {
temp.i = 0;
}
- static void temporaryReferenceConst(const NoBaseNoMember& temp) {}
+ static void temporaryReferenceConst(const NoBaseNoMember& temp) {
+ temp.i = 0;
+ }
};
class NoBaseNoMember0 {
diff --git a/cpp/random.cpp b/cpp/random.cpp
deleted file mode 100644
index 3e02809..0000000
--- a/cpp/random.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "common.hpp"
-
-int main() {
- /*
- # random_device
-
- Ultimate C++11 method to seed a PRNG, wraps over `/dev/urandom`.
-
- http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand/13004555#13004555
- */
- {
- std::random_device dev;
- unsigned int seed = dev();
- std::mt19937 prng(seed);
- std::uniform_int_distribution<> dist(1, 10);
- for (unsigned int i = 0; i < 10; ++i) {
- // std::cout << dist(prng) << std::endl;
- }
- }
-}
diff --git a/cpp/set.cpp b/cpp/set.cpp
index fab1b65..d77889c 100644
--- a/cpp/set.cpp
+++ b/cpp/set.cpp
@@ -1,14 +1,14 @@
/*
# set
- - unique elements: inserting twice does nothing
+Implemented with Red Black trees in GCC 6.4:
+https://stackoverflow.com/questions/2558153/what-is-the-underlying-data-structure-of-a-stl-set-in-c/51944661#51944661
- - always ordered: $O(log)$ find / insert
+A hashtable would be unlikely because it is sorted and can be efficiently iterated.
- - immutable elements: it is not possible to modify an object,
- one must first remove it and resinsert.
+Unique elements: inserting twice does nothing.
- This is so because modification may mean reordering.
+Immutable elements: it is not possible to modify an object, one must first remove it and resinsert. This is so because modification may mean reordering.
*/
#include "common.hpp"
@@ -81,7 +81,7 @@ int main() {
/*
# insert
- Return is a pair conatining:
+ Return is a pair containing:
- if the item was not present, an iterator to the item inserted and true
- if the item was present, an iterator to the existing item inserted and false
diff --git a/eigen/Makefile b/eigen/Makefile
new file mode 120000
index 0000000..cbd0d3e
--- /dev/null
+++ b/eigen/Makefile
@@ -0,0 +1 @@
+../Makefile_many
\ No newline at end of file
diff --git a/eigen/Makefile_params b/eigen/Makefile_params
new file mode 100644
index 0000000..fa0330a
--- /dev/null
+++ b/eigen/Makefile_params
@@ -0,0 +1 @@
+CXXFLAGS_EXTRA := $(shell pkg-config --cflags eigen3)
diff --git a/eigen/README.md b/eigen/README.md
new file mode 100644
index 0000000..d715f35
--- /dev/null
+++ b/eigen/README.md
@@ -0,0 +1,41 @@
+# Eigen
+
+https://eigen.tuxfamily.org/
+
+Tested on Eigen 3.3.4.
+
+## SVD
+
+Calculate the SVD decomposition: https://en.wikipedia.org/wiki/Singular-value_decomposition
+
+ ./svd.out
+
+Output:
+
+ E
+ 9.52552
+ 0.5143
+
+ U
+ 0.229848 -0.883461 0.408249
+ 0.524745 -0.240783 -0.816496
+ 0.819642 0.401896 0.408248
+
+ UU'
+ 1 -5.96046e-08 5.96046e-08
+ -5.96046e-08 1 5.96046e-08
+ 5.96046e-08 5.96046e-08 1
+
+ V
+ 0.61963 0.784894
+ 0.784894 -0.61963
+
+ VV'
+ 1 0
+ 0 1
+
+ least squares
+ -1.33333
+ 1.08333
+
+This shows how `U` and `V` are unitary.
diff --git a/eigen/configure b/eigen/configure
new file mode 100755
index 0000000..0bf6b25
--- /dev/null
+++ b/eigen/configure
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+sudo aptitude update
+# BLAS C/Fotran and LAPACK Fortran:
+sudo aptitude install liblapack-dev liblapacke-dev
+# Lapack C via LAPACKE:
+# TODO: how to install on Ubuntu 12.04?
+# The following works only on later Ubuntu
+#sudo aptitude install liblapacke-dev
diff --git a/eigen/svd.cpp b/eigen/svd.cpp
new file mode 100644
index 0000000..76ee651
--- /dev/null
+++ b/eigen/svd.cpp
@@ -0,0 +1,37 @@
+/* Adapted from: https://eigen.tuxfamily.org/dox/classEigen_1_1JacobiSVD.html */
+
+#include
+using std::cout;
+using std::endl;
+
+#include
+#include
+using Eigen::ComputeFullU;
+using Eigen::ComputeFullV;
+using Eigen::DiagonalMatrix;
+using Eigen::JacobiSVD;
+using Eigen::MatrixXf;
+using Eigen::Vector3f;
+
+int main() {
+ MatrixXf m(3,2);
+ m <<
+ 1.0, 2.0,
+ 3.0, 4.0,
+ 5.0, 6.0
+ ;
+ JacobiSVD svd(m, ComputeFullU | ComputeFullV);
+ auto e = svd.singularValues();
+ // TODO. e needs to be 3x2, what is the nicest way? Almost there, but this changes value positions.
+ //MatrixXf e(svd.singularValues().asDiagonal());
+ //e.resize(m.rows(), m.cols());
+ cout << "E" << endl << e << endl << endl;
+ auto u = svd.matrixU();
+ cout << "U" << endl << u << endl << endl;
+ cout << "UU'" << endl << u.adjoint() * u << endl << endl;
+ auto v = svd.matrixV();
+ cout << "V" << endl << v << endl << endl;
+ cout << "VV'" << endl << v * v.adjoint() << endl << endl;
+ //cout << "UEV" << endl << u * e * v << endl << endl;
+ cout << "least squares" << endl << svd.solve(Vector3f(1, 0, 0)) << endl << endl;
+}
diff --git a/gcc/asm.c b/gcc/asm.c
index 0ae76ff..d5b613c 100644
--- a/gcc/asm.c
+++ b/gcc/asm.c
@@ -4,57 +4,74 @@ int main(void) {
#if defined(__i386__) || defined(__x86_64__)
puts("__i386__ || __x86_64__");
- /*
- # Basic asm vs extended asm
-
- There are two types of asm: basic and extended.
-
- The basic one does not have a colon after the string.
-
- Basic is strictly less powerful: it can only deal with literal commands,
- so you basically (badum tish) never want to use it.
-
- All other examples in this section are extended asm.
-
- https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Extended-Asm.html
- */
+ /* # Basic asm vs extended asm
+ *
+ * There are two types of asm: basic and extended.
+ *
+ * The basic one does not have a colon after the string.
+ *
+ * Basic is strictly less powerful: it can only deal with literal commands,
+ * so you basically (badum tish) never want to use it.
+ *
+ * All other examples in this section are extended asm.
+ *
+ * https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Extended-Asm.html
+ */
{
#ifdef __i386__
- __asm__ __volatile__ ("push %eax; mov $1, %eax; pop %eax;");
+ asm ("push %eax; mov $1, %eax; pop %eax;");
#else
- __asm__ __volatile__ ("push %rax; mov $1, %rax; pop %rax;");
+ asm ("push %rax; mov $1, %rax; pop %rax;");
#endif
}
- /*
- # m constraint
-
- Memory.
-
- Instructs GCC to keep value of given expressions into RAM.
-
- This is the most basic way to get/set values of C variables in assembly code.
- */
+ /* # m constraint
+ *
+ * Memory.
+ *
+ * Instructs GCC to keep value of given expressions into RAM.
+ *
+ * This is the most basic way to get/set values of C variables in assembly code.
+ */
{
- uint32_t in = 1;
- uint32_t out = 0;
- __asm__ __volatile__ (
- "movl %1, %%eax;"
- "inc %%eax;"
- "movl %%eax, %0"
- : "=m" (out) /* Outputs. '=' means written to. */
- : "m" (in) /* Inputs. No '='. */
- : "%eax"
- );
- assert(out == in + 1);
+ /* OK */
+ {
+ uint32_t in = 1;
+ uint32_t out = 0;
+ asm (
+ "movl %1, %%eax;"
+ "inc %%eax;"
+ "movl %%eax, %0"
+ : "=m" (out) /* Outputs. '=' means written to. */
+ : "m" (in) /* Inputs. No '='. */
+ : "%eax"
+ );
+ assert(out == in + 1);
+ }
+
+ /* ERROR: memory input 1 is not directly addressable */
+ /*
+ {
+ uint32_t out = 0;
+ asm (
+ "movl %1, %%eax;"
+ "inc %%eax;"
+ "movl %%eax, %0"
+ : "=m" (out)
+ : "m" (1)
+ : "%eax"
+ );
+ assert(out == 1 + 1);
+ }
+ */
}
- /* Multiple inputs. */
- {
+ /* Multiple inputs. */
+ {
uint32_t in0 = 1;
uint32_t in1 = 2;
uint32_t out = 0;
- __asm__ __volatile__ (
+ asm (
"movl %1, %%eax;"
"movl %2, %%ebx;"
"addl %%ebx, %%eax;"
@@ -74,13 +91,13 @@ int main(void) {
* We must mark it as `+` which means that the memory is used for both read and write. */
{
uint32_t io = 0;
- __asm__ __volatile__ (
- "movl %0, %%eax;"
- "inc %%eax;"
- "movl %%eax, %0;"
- : "+m" (io) /* + means both read and written to. */
- : /* No input. */
- : "%eax"
+ asm (
+ "movl %0, %%eax;"
+ "inc %%eax;"
+ "movl %%eax, %0;"
+ : "+m" (io) /* + means both read and written to. */
+ : /* No input. */
+ : "%eax"
);
assert(io == 1);
}
@@ -90,7 +107,7 @@ int main(void) {
float in = 1.0;
float out = 0.0;
/* out = -in */
- __asm__ __volatile__ (
+ asm (
"flds %1;"
"fchs;"
"fstps %0;"
@@ -100,40 +117,38 @@ int main(void) {
assert(out == -1.0);
}
- /*
- # Register constraints
-
- https://gcc.gnu.org/onlinedocs/gcc/Simple-Constraints.html
-
- Tell GCC to automatically read memory into registers or write registers into memory
-
- This is more precise and complicated than using `m`:
-
- - r: gcc chooses any free register
- - a: %eax
- - b: %ebx
- - c: %ecx
- - d: %edx
- - S: %esi
- - D: %edi
- - 0: matching register
- */
-
- /*
- # r register constraint
-
- GCC will automatically put the value of `in` from RAM into a register for us
- and `out` from a register into ram at the end
-
- GCC just makes sure they are written from/to memory before/after the operations.
-
- This is great, as it:
-
- - makes our assembly shorter: no memory moves nor clobbers are needed
- - allows GCC to optimize further
- */
+ /* # Register constraints
+ *
+ * https://gcc.gnu.org/onlinedocs/gcc/Simple-Constraints.html
+ *
+ * Tell GCC to automatically read memory into registers or write registers into memory
+ *
+ * This is more precise and complicated than using `m`:
+ *
+ * - r: gcc chooses any free register
+ * - a: %eax
+ * - b: %ebx
+ * - c: %ecx
+ * - d: %edx
+ * - S: %esi
+ * - D: %edi
+ * - 0: matching register
+ */
+
+ /* # r register constraint
+ *
+ * GCC will automatically put the value of `in` from RAM into a register for us
+ * and `out` from a register into ram at the end
+ *
+ * GCC just makes sure they are written from/to memory before/after the operations.
+ *
+ * This is great, as it:
+ *
+ * - makes our assembly shorter: no memory moves nor clobbers are needed
+ * - allows GCC to optimize further
+ */
{
- const uint32_t in0 = 0;
+ const uint32_t in0 = 0;
uint32_t in = in0;
uint32_t out = 0;
asm (
@@ -148,17 +163,17 @@ int main(void) {
}
/*
- # 0 matching constraint
-
- Specifies that an input maps to the same as a given output.
-
- https://stackoverflow.com/questions/48381184/can-i-modify-input-operands-in-gcc-inline-assembly/48381252#48381252
-
- - vs '+': allows biding two different variables
- - vs 'a': allows referring to an 'r', which is automatically allocated by GCC
- */
+ * # 0 matching constraint
+ *
+ * Specifies that an input maps to the same as a given output.
+ *
+ * https://stackoverflow.com/questions/48381184/can-i-modify-input-operands-in-gcc-inline-assembly/48381252#48381252
+ *
+ * - vs '+': allows biding two different variables
+ * - vs 'a': allows referring to an 'r', which is automatically allocated by GCC
+ */
{
- const uint32_t in0 = 1;
+ const uint32_t in0 = 1;
uint32_t in = in0;
uint32_t out = 0;
asm (
@@ -170,15 +185,14 @@ int main(void) {
assert(out == in0 + 1);
}
- /*
- # a register constraint
-
- Forces it to be put into eax.
-
- Clobber done automatically for us.
-
- Just use 'r' whenever you can.
- */
+ /* # a register constraint
+ *
+ * Forces it to be put into eax.
+ *
+ * Clobber done automatically for us.
+ *
+ * Just use 'r' whenever you can.
+ */
{
uint32_t x = 0;
asm (
@@ -189,13 +203,12 @@ int main(void) {
assert(x == 1);
}
- /*
- # Register variables
-
- http://stackoverflow.com/questions/2114163/reading-a-register-value-into-a-c-variable
-
- https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Explicit-Reg-Vars.html
- */
+ /* # Register variables
+ *
+ * http://stackoverflow.com/questions/2114163/reading-a-register-value-into-a-c-variable
+ *
+ * https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Explicit-Reg-Vars.html
+ */
{
register uint32_t eax asm ("eax");
asm ("mov $1, %%eax;" : : : "%eax");
diff --git a/gcc/asm.md b/gcc/asm.md
index 7eab1e2..2c040bf 100644
--- a/gcc/asm.md
+++ b/gcc/asm.md
@@ -45,9 +45,10 @@ where:
Both inputs and outputs are constraints. `X` will indicate the constraint type
-# __asm__ vs asm
+## __asm__ vs asm
-
+-
+-
## Double percent
diff --git a/gcc/build.md b/gcc/build.md
index 7fe38c8..a83091a 100644
--- a/gcc/build.md
+++ b/gcc/build.md
@@ -4,35 +4,36 @@ How to build GCC from source.
Tested with: version 5.1.0 on Ubuntu 14.04 in a 2013 computer.
-Summary:
+Summary local build:
sudo apt-get build-dep gcc
# Required to compile gnat.
sudo apt-get install gnat-4.8
- mkdir gcc
+ git clone git://gcc.gnu.org/git/gcc.git
cd gcc
- git clone git://gcc.gnu.org/git/gcc.git src
- cd src
# No annotated tags... so no describe.
git checkout gcc-5_1_0-release
./contrib/download_prerequisites
- cd ..
mkdir build
cd build
# C and C++ only.
- ../src/configure --enable-languages=c,c++ --prefix="$(pwd)/../install"
+ ../configure --enable-languages=c,c++ --prefix="$(pwd)/install"
# Add a suffix to the executable names:
# --program-suffix="-4.7"
# All languages.
- # ../src/configure --enable-languages=all --prefix="$(pwd)/../install"
+ # ../configure --enable-languages=all --prefix="$(pwd)/install"
# Wait hours.
- make -j5
+ make -j$(nproc)
+
# Wait hours.
- make check
+ #make check
+
# Install executables to /usr/local/bin
# There are also many other installed files under /usr/local.
- sudo make install
- gcc -v
+ make install
+
+ # Use it.
+ ./install/bin/gcc -v
# sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9
Or install locally for interactive testing:
diff --git a/gcc/statement_expression.c b/gcc/statement_expression.c
index 25e1c9d..9109f23 100644
--- a/gcc/statement_expression.c
+++ b/gcc/statement_expression.c
@@ -1,14 +1,35 @@
/*
-## Statement expression
+# Statement expression
- https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
+Only the last expression is "returned".
- Only the last expression is returned.
+Especially useful for macros:
+https://stackoverflow.com/questions/10393844/about-typecheck-in-linux-kernel
+where it serves as a "return value"
+
+https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
*/
+#define FACTORIAL(X) \
+ ({ \
+ unsigned int x = X; \
+ unsigned int result = 1; \
+ while (x > 1) { \
+ result *= x; \
+ x--; \
+ } \
+ result; \
+ })
+
#include "common.h"
int main() {
- assert(({int i = 0; int j = i; i++; j = i; j;}));
+ /* Minimal example */
+ int x = ({int i = 0; i++; i + 1;});
+ assert(x == 2);
+
+ /* More meaningful macro example*/
+ assert(FACTORIAL(5) == 120);
+
return EXIT_SUCCESS;
}
diff --git a/gcc/typeof.c b/gcc/typeof.c
index b47ee43..d3df245 100644
--- a/gcc/typeof.c
+++ b/gcc/typeof.c
@@ -1,9 +1,11 @@
/*
# typeof
- Like C++11 decltype.
+Like C++11 decltype.
- Partially reproductible with C11 `_Generic`.
+Partially reproductible with C11 `_Generic`.
+
+https://stackoverflow.com/questions/6513806/would-it-be-possible-to-add-type-inference-to-the-c-language/31709221#31709221
*/
#include "common.h"
@@ -12,5 +14,10 @@ int main() {
/* Same as: double j = 0.5; */
typeof(1 + 0.5) j = 0.5;
assert(j == 0.5);
+
+ /* Similar to C++ auto. */
+ __auto_type k = 0.5;
+ assert(sizeof(j) == sizeof(k));
+
return EXIT_SUCCESS;
}
diff --git a/gdb/Makefile b/gdb/Makefile
index 8b66f0a..6981794 100644
--- a/gdb/Makefile
+++ b/gdb/Makefile
@@ -1,27 +1,30 @@
.POSIX:
-G ?= gdb3
-IN_EXT ?= .c
-IN_EXT_CPP ?= .cpp
-O ?= 0
-OUT_EXT ?= .out
-RUN ?= count_infinite
-
-INS := $(wildcard *$(IN_EXT))
-OUTS := $(addsuffix $(OUT_EXT), $(basename $(INS)))
-
-INS_CPP := $(wildcard *$(IN_EXT_CPP))
-OUTS_CPP := $(addsuffix $(OUT_EXT), $(basename $(INS_CPP)))
+COMMON_FLAGS = -O'$O' -g'$(G)' -pthread -Wextra
+CFLAGS = $(COMMON_FLAGS) -std=c99
+CXXFLAGS = $(COMMON_FLAGS) -std=c++11
+G = gdb3
+IN_EXT = .c
+IN_EXT_CPP = .cpp
+O = 0
+OUT_EXT = .out
+RUN = count_infinite
+
+INS = $(wildcard *$(IN_EXT))
+OUTS = $(addsuffix $(OUT_EXT), $(basename $(INS)))
+
+INS_CPP = $(wildcard *$(IN_EXT_CPP))
+OUTS_CPP = $(addsuffix $(OUT_EXT), $(basename $(INS_CPP)))
.PHONY: all clean run
all: $(OUTS) $(OUTS_CPP)
%$(OUT_EXT): %$(IN_EXT)
- gcc -O'$O' -g'$(G)' -o '$@' -pedantic-errors -std=c89 -Wextra '$<'
+ gcc $(CFLAGS) -o '$@' -pedantic-errors '$<'
%$(OUT_EXT): %$(IN_EXT_CPP)
- g++ -O'$O' -g'$(G)' -o '$@' -pedantic-errors -std=c++11 -Wextra '$<'
+ g++ $(CXXFLAGS) -o '$@' -pedantic-errors '$<'
clean:
rm -f *$(OUT_EXT)
diff --git a/gdb/README.md b/gdb/README.md
index 661e00a..4f03d5b 100644
--- a/gdb/README.md
+++ b/gdb/README.md
@@ -29,6 +29,7 @@ Tested on 7.7.1 unless mentioned otherwise.
1. [Overload](overload.cpp)
1. [Method](method.cpp)
1. [Polymorphism](polymorphism.cpp)
+ 1. [Threads](threads.c)
1. [gdbserver](gdbserver.md)
1. GDB scripts
1. [step_all](step_all.gdb)
diff --git a/gdb/run b/gdb/run
index 4e725e9..ad38e81 100755
--- a/gdb/run
+++ b/gdb/run
@@ -1,11 +1,10 @@
#!/usr/bin/env bash
-
-# Usage: try either of:
-#
-# run watch
-# run watch.
-# run watch.c
-# run watch.out
-
+set -eu
f="${1%.*}"
-gdb -batch -nh -x "${f}.gdb" "${f}.out"
+g="${f}.gdb"
+if [ -f "$g" ]; then
+ gdbcmd="-batch -x $g"
+else
+ gdbcmd=
+fi
+gdb -nh -q $gdbcmd "${f}.out"
diff --git a/gdb/threads.c b/gdb/threads.c
new file mode 100644
index 0000000..95d77da
--- /dev/null
+++ b/gdb/threads.c
@@ -0,0 +1,47 @@
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+void* thread_0(void *arg) {
+ int i;
+ i = 0;
+ while (true) {
+ printf("t0 %d\n", i);
+ sleep(1);
+ i++;
+ }
+ return NULL;
+}
+
+void* thread_1(void *arg) {
+ int i;
+ i = 0;
+ while (true) {
+ printf("t1 %d\n", i);
+ sleep(1);
+ i++;
+ }
+ return NULL;
+}
+
+int main(void) {
+ enum NUM_THREADS {NUM_THREADS = 2};
+ pthread_t threads[NUM_THREADS];
+ int thread_args[NUM_THREADS];
+ int i;
+ pthread_create(&threads[0], NULL, thread_0, (void*)&thread_args[0]);
+ pthread_create(&threads[1], NULL, thread_1, (void*)&thread_args[1]);
+ pthread_setname_np(threads[1], "myname1");
+ while (true) {
+ printf("main %d\n", i);
+ sleep(1);
+ i++;
+ }
+ return EXIT_SUCCESS;
+}
diff --git a/gdb/threads.md b/gdb/threads.md
new file mode 100644
index 0000000..12450b6
--- /dev/null
+++ b/gdb/threads.md
@@ -0,0 +1,94 @@
+# Threads
+
+Run:
+
+ ./run threads
+
+Inside GDB:
+
+ run
+
+Then:
+
+ Ctrl + C
+
+All threads stop.
+
+## Get backtraces for all threads
+
+https://stackoverflow.com/questions/18391808/how-to-get-the-backtrace-for-all-the-threads-in-gdb
+
+ thread apply all bt
+
+Sample output:
+
+ Thread 3 (Thread 0x7ffff6fee700 (LWP 29344)):
+ #0 0x00007ffff78bc30d in nanosleep () at ../sysdeps/unix/syscall-template.S:84
+ #1 0x00007ffff78bc25a in __sleep (seconds=0) at ../sysdeps/posix/sleep.c:55
+ #2 0x0000000000400839 in thread_1 (arg=0x7fffffffcf0c) at threads.c:33
+ #3 0x00007ffff7bc16ba in start_thread (arg=0x7ffff6fee700) at pthread_create.c:333
+ #4 0x00007ffff78f741d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
+
+ Thread 2 (Thread 0x7ffff77ef700 (LWP 29343)):
+ #0 0x00007ffff78bc30d in nanosleep () at ../sysdeps/unix/syscall-template.S:84
+ #1 0x00007ffff78bc25a in __sleep (seconds=0) at ../sysdeps/posix/sleep.c:55
+ #2 0x000000000040075b in thread_0 (arg=0x7fffffffcf08) at threads.c:19
+ #3 0x00007ffff7bc16ba in start_thread (arg=0x7ffff77ef700) at pthread_create.c:333
+ #4 0x00007ffff78f741d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
+
+ Thread 1 (Thread 0x7ffff7fc7700 (LWP 29339)):
+ #0 nanosleep () at ../sysdeps/unix/syscall-template.S:85
+ #1 0x00007ffff78bc25a in __sleep (seconds=0) at ../sysdeps/posix/sleep.c:55
+ #2 0x00000000004008b9 in main () at threads.c:48
+
+So we see that there are three threads:
+
+- `1` which is the `main`
+- `2` and `3` which we created ourselves
+
+all of which are very likely inside sleep.
+
+A few more information we can extract:
+
+ LWP 29339
+
+means:
+
+- `LWP`: Light Weight Process
+- `29339`: thread ID
+
+If we also get the process ID with :
+
+ info inferior
+
+then we can confirm the thread ID under `/proc`:
+
+ ls /proc//task/
+
+The part:
+
+ Thread 0x7ffff77ef700
+
+gives us value of `pthread_t` . This can be confirmed with:
+
+ thread 1
+ up 2
+ p/x threads
+
+## More basic things
+
+Switch to a thread:
+
+ thread 1
+
+Now the usual commands like `bt`, `info registers`, etc. will apply to that thread.
+
+List all threads:
+
+ info threads
+
+This shows one extra information that `thread apply all bt` does not: the thread name:
+
+ myname1
+
+which defaults to the executable name, but which we have modified for the thread 1 with `pthread_setname_np`, see also:
diff --git a/glibc/README.md b/glibc/README.md
index 54408ff..c1b52f8 100644
--- a/glibc/README.md
+++ b/glibc/README.md
@@ -7,6 +7,7 @@
1. [main.c](main.c)
1. [ptrace.c](ptrace.c)
1. [reboot.c](reboot.c.off)
+ 1. [sched.c](sched.c)
1. [syscall.c](syscall.c)
1. `string.h`
1. [strverscmp.c](strverscmp.c)
diff --git a/glibc/main.c b/glibc/main.c
index c1f126e..e2d198f 100644
--- a/glibc/main.c
+++ b/glibc/main.c
@@ -66,51 +66,6 @@ int main() {
}
}
- /*
- # sched.h
-
- More scheduling policies are defined.
-
- Those constants have the same meaning as in the kernel code versions.
- */
- {
- printf("SCHED_BATCH = %d\n", SCHED_BATCH);
- printf("SCHED_IDLE = %d\n", SCHED_IDLE );
-
- /* Called SCHED_NORMAL in the kernel: */
- printf("SCHED_OTHER = %d\n", SCHED_OTHER);
-
- /*
- # sched_getaffinity
-
- view in which cpu's the given process can run
-
- Linux keeps track of this, and this can be set with appropriate premissions
-
- # sched_setaffinity
-
- set for getaffinity
-
- # cpu_set_t
-
- a bitmap with a field per cpu
- */
- {
- cpu_set_t mask;
- if (sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
- perror("sched_getaffinity");
- exit(EXIT_FAILURE);
- } else {
- printf("sched_getaffinity = ");
- unsigned int i;
- for (i = 0; i < sizeof(cpu_set_t); i++) {
- printf("%d", CPU_ISSET(0, &mask));
- }
- printf("\n");
- }
- }
- }
-
/*
# unistd.h
*/
diff --git a/glibc/sched.c b/glibc/sched.c
new file mode 100644
index 0000000..b92f001
--- /dev/null
+++ b/glibc/sched.c
@@ -0,0 +1,69 @@
+/*
+- https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity2-and-sched-setaffinity2-please-give-code-samp
+- https://stackoverflow.com/questions/766395/how-does-sched-setaffinity-work
+- https://stackoverflow.com/questions/8336191/how-to-prevent-inheriting-cpu-affinity-by-child-forked-process
+- https://unix.stackexchange.com/questions/73/how-can-i-set-the-processor-affinity-of-a-process-on-linux/441098#441098
+
+Also try to this program with something like:
+
+ taskset -c 1-3 ./sched.out
+
+# sched.h
+
+ More scheduling policies are defined.
+
+ Those constants have the same meaning as in the kernel code versions.
+*/
+
+#include "common.h"
+
+void print_affinity() {
+ cpu_set_t mask;
+ long nproc, i;
+
+ if (sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
+ perror("sched_getaffinity");
+ assert(false);
+ } else {
+ nproc = sysconf(_SC_NPROCESSORS_ONLN);
+ printf("sched_getaffinity = ");
+ for (i = 0; i < nproc; i++) {
+ printf("%d ", CPU_ISSET(i, &mask));
+ }
+ printf("\n");
+ }
+}
+
+int main(void) {
+ printf("SCHED_BATCH = %d\n", SCHED_BATCH);
+ printf("SCHED_IDLE = %d\n", SCHED_IDLE );
+ /* Called SCHED_NORMAL in the kernel: */
+ printf("SCHED_OTHER = %d\n", SCHED_OTHER);
+
+ /*
+ # sched_getaffinity
+
+ View in which cpu's the given process can run.
+
+ Linux keeps track of this, and this can be set with appropriate premissions.
+
+ 0 means getpid().
+ */
+ {
+ cpu_set_t mask;
+
+ print_affinity();
+ printf("sched_getcpu = %d\n", sched_getcpu());
+ CPU_ZERO(&mask);
+ CPU_SET(0, &mask);
+ if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
+ perror("sched_setaffinity");
+ assert(false);
+ }
+ print_affinity();
+ /* TODO is it guaranteed to have taken effect already? Always worked on my tests. */
+ printf("sched_getcpu = %d\n", sched_getcpu());
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/lapack/c.c b/lapack/c.c
index 0d37554..0d50e09 100644
--- a/lapack/c.c
+++ b/lapack/c.c
@@ -1,8 +1,8 @@
/*
-How to use blas and lapack with the standard
-interfaces provided by their respective projects, repectively through
-`cblas.h` and `lapacke.h`
-*/
+ * How to use blas and lapack with the standard
+ * interfaces provided by their respective projects, repectively through
+ * `cblas.h` and `lapacke.h`
+ */
#include
#include
@@ -13,8 +13,7 @@ interfaces provided by their respective projects, repectively through
#include
#include
-/**
- * assert two integers are equal
+/* Assert two integers are equal.
* if not, print them to stderr and assert false
*/
void assert_eqi(int i1, int i2) {
@@ -24,9 +23,8 @@ void assert_eqi(int i1, int i2) {
}
}
-/**
- * assert two doubles are equal within err precision
- * if not, print them to stderr
+/* Assert two doubles are equal within err precision
+ * If not, print them to stderr
*/
void assert_eqd(double d1, double d2, double err) {
if (fabs(d1 - d2) > err) {
@@ -35,7 +33,7 @@ void assert_eqd(double d1, double d2, double err) {
}
}
-/** print an array of doubles to stderr */
+/* print an array of doubles to stderr */
void print_vecd(int n, double * v) {
int i;
for (i=0; i 0
+ scons x=1
+ ./main.out
+ # => 1
+ scons x=0
+ ./main.out
+ # => 0
diff --git a/scons/default/README.md b/scons/default/README.md
new file mode 100644
index 0000000..439dbd9
--- /dev/null
+++ b/scons/default/README.md
@@ -0,0 +1,21 @@
+# Default
+
+ cd src0
+
+ scons
+ ./main.out
+ # => No such file or directory.
+ ../src1/main.out
+ # => 1
+
+ scons ..
+ ./main.out
+ # => 0
+ ../src1/main.out
+ # => 1
+
+By default, SCons builds all targets under the current directory and descendants.
+
+If `Default()` is given, it change that default to the given programs.
+
+You can always go back to recurse under a given directory with `scons path/to/dir`.
diff --git a/scons/default/src0/SConstruct b/scons/default/src0/SConstruct
new file mode 100644
index 0000000..737f8f2
--- /dev/null
+++ b/scons/default/src0/SConstruct
@@ -0,0 +1,4 @@
+env = Environment()
+p0 = env.Program(target='main.out', source=['main.c'])
+p1 = env.Program(target='../src1/main.out', source=['../src1/main.c'])
+env.Default(p1)
diff --git a/scons/default/src0/main.c b/scons/default/src0/main.c
new file mode 100644
index 0000000..62130df
--- /dev/null
+++ b/scons/default/src0/main.c
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ puts("0");
+}
diff --git a/scons/default/src1/main.c b/scons/default/src1/main.c
new file mode 100644
index 0000000..270e419
--- /dev/null
+++ b/scons/default/src1/main.c
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ puts("1");
+}
diff --git a/scons/sconscript/README.md b/scons/sconscript/README.md
new file mode 100644
index 0000000..6fd4c05
--- /dev/null
+++ b/scons/sconscript/README.md
@@ -0,0 +1,4 @@
+# SConscript
+
+ scons
+ ./src/main.out
diff --git a/scons/sconscript/SConstruct b/scons/sconscript/SConstruct
new file mode 100644
index 0000000..272066f
--- /dev/null
+++ b/scons/sconscript/SConstruct
@@ -0,0 +1,2 @@
+env = Environment()
+env.SConscript('src/SConscript')
diff --git a/scons/sconscript/scr b/scons/sconscript/scr
new file mode 100644
index 0000000..00af2ff
--- /dev/null
+++ b/scons/sconscript/scr
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ puts("hello");
+}
diff --git a/scons/sconscript/src/SConscript b/scons/sconscript/src/SConscript
new file mode 100644
index 0000000..5bc2b34
--- /dev/null
+++ b/scons/sconscript/src/SConscript
@@ -0,0 +1,2 @@
+env = Environment()
+env.Program(target='main.out', source=['main.c'])
diff --git a/scons/sconscript/src/main.c b/scons/sconscript/src/main.c
new file mode 100644
index 0000000..00af2ff
--- /dev/null
+++ b/scons/sconscript/src/main.c
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ puts("hello");
+}
diff --git a/scons/two-envs/README.md b/scons/two-envs/README.md
new file mode 100644
index 0000000..a765be1
--- /dev/null
+++ b/scons/two-envs/README.md
@@ -0,0 +1,9 @@
+# Two envs
+
+All declared envs with `Environment()` are built:
+
+ scons
+ ./build-0/main.out
+ # => 0
+ ./build-1/main.out
+ # => 1
diff --git a/scons/two-envs/SConstruct b/scons/two-envs/SConstruct
new file mode 100644
index 0000000..e60871c
--- /dev/null
+++ b/scons/two-envs/SConstruct
@@ -0,0 +1,14 @@
+import os.path
+
+def mkenv(x):
+ env = Environment()
+ env.Append(CPPDEFINES=['X=' + x])
+ variant_dir = 'build-{}'.format(x)
+ env.VariantDir(variant_dir, 'src', duplicate=0)
+ program = env.Program(
+ target=os.path.join(variant_dir, 'main.out'),
+ source=[os.path.join(variant_dir, 'main.c')]
+ )
+
+mkenv('0')
+mkenv('1')
diff --git a/scons/two-envs/src/main.c b/scons/two-envs/src/main.c
new file mode 100644
index 0000000..1d9e19c
--- /dev/null
+++ b/scons/two-envs/src/main.c
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ printf("%d\n", X);
+}
diff --git a/scons/variant-dir/README.md b/scons/variant-dir/README.md
new file mode 100644
index 0000000..ebcae40
--- /dev/null
+++ b/scons/variant-dir/README.md
@@ -0,0 +1,13 @@
+# Variant dir
+
+ scons
+ ./build-0/main.out
+ # => 0
+ scons x=1
+ ./build-1/main.out
+ # => 1
+
+We could do something more advanced by:
+
+- hash all input arguments like `x` and name the output directory after them
+- cat the input arguments to a file in that directory to enable identifying the directories
diff --git a/scons/variant-dir/SConstruct b/scons/variant-dir/SConstruct
new file mode 100644
index 0000000..2546784
--- /dev/null
+++ b/scons/variant-dir/SConstruct
@@ -0,0 +1,10 @@
+import os.path
+env = Environment()
+x = ARGUMENTS.get('x', '0')
+env.Append(CPPDEFINES=['X=' + x])
+variant_dir = 'build-{}'.format(x)
+env.VariantDir(variant_dir, 'src', duplicate=0)
+program1 = env.Program(
+ target=os.path.join(variant_dir, 'main.out'),
+ source=[os.path.join(variant_dir, 'main.c')]
+)
diff --git a/scons/variant-dir/src/main.c b/scons/variant-dir/src/main.c
new file mode 100644
index 0000000..1d9e19c
--- /dev/null
+++ b/scons/variant-dir/src/main.c
@@ -0,0 +1,5 @@
+#include
+
+int main(void) {
+ printf("%d\n", X);
+}
diff --git a/sdl/png.c b/sdl/png.c
index 7aac1dc..2b11a5c 100644
--- a/sdl/png.c
+++ b/sdl/png.c
@@ -1,13 +1,13 @@
-
-/*
-Basic texture example.
-
-Much faster than SDL_RenderDrawPoint calls.
-
-Uses GL textures under the hood.
-
-SDL_TEXTUREACCESS_STREAMING is key to allow us to write to the texture from CPU.
-*/
+/* Basic texture example.
+ *
+ * Much faster than SDL_RenderDrawPoint calls.
+ *
+ * Uses GL textures under the hood.
+ *
+ * SDL_TEXTUREACCESS_STREAMING is key to allow us to write to the texture from CPU.
+ *
+ * https://gamedev.stackexchange.com/questions/59078/sdl-function-for-loading-pngs/135894#135894
+ */
#include "common.h"
diff --git a/shared-library/basic/Makefile b/shared-library/basic/Makefile
index c566df9..fd8bf08 100644
--- a/shared-library/basic/Makefile
+++ b/shared-library/basic/Makefile
@@ -1,13 +1,15 @@
-CC := gcc -ggdb3 -pedantic-errors -std=c89 -Wall -Wextra
+CC_DL = gcc -ggdb3 -std=c89 -Wall -Wextra
+CC = $(CC_DL) -pedantic-errors
.PHONY: all clean run
-all: maina.out mainso.out mainso_fullpath.out
+all: maina.out mainso.out mainso_fullpath.out dlopen.out
run: all
./maina.out
LD_LIBRARY_PATH=. ./mainso.out
./mainso_fullpath.out
+ LD_LIBRARY_PATH=. ./dlopen.out
mainso.out: main.o libcirosantilli_ab.so
@# Will look for lib with basename *exactly* `libcirosantilli_ab.so`,
@@ -37,6 +39,17 @@ mainso_fullpath.out: main.o libcirosantilli_ab.so
maina.out: main.o ab.a
$(CC) main.o ab.a -o maina.out
+# If we use -pedantic-errors, build fails:
+#
+# ISO C forbids conversion of object pointer to function pointer type
+#
+# There seems to be no no undefined way of doing it:
+# https://stackoverflow.com/questions/14134245/iso-c-void-and-function-pointers
+#
+# -dl required otherwise: https://stackoverflow.com/questions/956640/linux-c-error-undefined-reference-to-dlopen
+dlopen.out: dlopen.c
+ $(CC_DL) -o '$@' '$<' -ldl
+
libcirosantilli_ab.so: a.o b.o
$(CC) -shared a.o b.o -o libcirosantilli_ab.so
@# Same?
diff --git a/shared-library/basic/README.md b/shared-library/basic/README.md
index ae53e55..f0083a5 100644
--- a/shared-library/basic/README.md
+++ b/shared-library/basic/README.md
@@ -1,7 +1,3 @@
# Basic
-Basic example. Creates a shared and a static library from `a.c` and `b.c`, and uses them in the following ways:
-
-- `maina.out`: uses the static library
-- `mainso.out`: uses the `.so` library with basename only
-- `mainso_fullpath.out`: uses the `.so` with the fullpath
+Basic example. Creates a shared and a static library from `a.c` and `b.c`.
diff --git a/shared-library/basic/a.c b/shared-library/basic/a.c
index b7dcf22..f8cc9b0 100644
--- a/shared-library/basic/a.c
+++ b/shared-library/basic/a.c
@@ -1,12 +1,9 @@
-#include
-
-/*
-Not mandatory in this example since we define the function here.
-
-But still a good idea to ensure that the prototypes are compatible.
-
-Often required because of header struct declarations.
-*/
+/* Not mandatory in this example since we define the function here.
+ *
+ * But still a good idea to ensure that the prototypes are compatible.
+ *
+ * Often required because of header struct declarations.
+ */
#include "a.h"
-void a(void) { puts("a"); }
+int a(void) { return 1; }
diff --git a/shared-library/basic/a.h b/shared-library/basic/a.h
index 733fc06..d72f9ff 100644
--- a/shared-library/basic/a.h
+++ b/shared-library/basic/a.h
@@ -1,6 +1,6 @@
#ifndef A_H
#define A_H
-void a(void);
+int a(void);
#endif
diff --git a/shared-library/basic/b.c b/shared-library/basic/b.c
index e1d66d3..f5ece7c 100644
--- a/shared-library/basic/b.c
+++ b/shared-library/basic/b.c
@@ -1,5 +1,3 @@
-#include
-
#include "b.h"
-void b(void) { puts("b"); }
+int b(void) { return 2; }
diff --git a/shared-library/basic/b.h b/shared-library/basic/b.h
index 9bc5877..495df22 100644
--- a/shared-library/basic/b.h
+++ b/shared-library/basic/b.h
@@ -1,6 +1,6 @@
#ifndef B_H
#define B_H
-void b(void);
+int b(void);
#endif
diff --git a/shared-library/basic/dlopen.c b/shared-library/basic/dlopen.c
new file mode 100644
index 0000000..cd53b64
--- /dev/null
+++ b/shared-library/basic/dlopen.c
@@ -0,0 +1,33 @@
+#define _XOPEN_SOURCE 700
+#include
+#include
+#include
+#include
+
+#include "a.h"
+#include "b.h"
+
+int main() {
+ void *handle;
+ int (*a)(void);
+ int (*b)(void);
+ char *error;
+
+ handle = dlopen("libcirosantilli_ab.so", RTLD_LAZY);
+ if (!handle) {
+ fprintf(stderr, "%s\n", dlerror());
+ exit(EXIT_FAILURE);
+ }
+ dlerror();
+ a = (int (*)(void)) dlsym(handle, "a");
+ b = (int (*)(void)) dlsym(handle, "b");
+ error = dlerror();
+ if (error != NULL) {
+ fprintf(stderr, "%s\n", error);
+ exit(EXIT_FAILURE);
+ }
+ assert(a() == 1);
+ assert(b() == 2);
+ dlclose(handle);
+ return EXIT_SUCCESS;
+}
diff --git a/shared-library/basic/main.c b/shared-library/basic/main.c
index b2da9e2..1041d63 100644
--- a/shared-library/basic/main.c
+++ b/shared-library/basic/main.c
@@ -1,11 +1,11 @@
-#include
+#include
#include
#include "a.h"
#include "b.h"
int main(void) {
- a();
- b();
+ assert(a() == 1);
+ assert(b() == 2);
return EXIT_SUCCESS;
}
diff --git a/shared-library/lib-lib-dependency/a.c b/shared-library/lib-lib-dependency/a.c
index 2d6349f..0800b98 100644
--- a/shared-library/lib-lib-dependency/a.c
+++ b/shared-library/lib-lib-dependency/a.c
@@ -3,7 +3,6 @@
#include "a.h"
#include "b.h"
-void a(void) {
- puts("a");
- b();
+int a(void) {
+ return b() + 1;
}
diff --git a/shared-library/lib-lib-dependency/a.h b/shared-library/lib-lib-dependency/a.h
index 733fc06..d72f9ff 100644
--- a/shared-library/lib-lib-dependency/a.h
+++ b/shared-library/lib-lib-dependency/a.h
@@ -1,6 +1,6 @@
#ifndef A_H
#define A_H
-void a(void);
+int a(void);
#endif
diff --git a/shared-library/lib-lib-dependency/b.c b/shared-library/lib-lib-dependency/b.c
index e1d66d3..48785b3 100644
--- a/shared-library/lib-lib-dependency/b.c
+++ b/shared-library/lib-lib-dependency/b.c
@@ -2,4 +2,4 @@
#include "b.h"
-void b(void) { puts("b"); }
+int b(void) { return 2; }
diff --git a/shared-library/lib-lib-dependency/b.h b/shared-library/lib-lib-dependency/b.h
index 9bc5877..495df22 100644
--- a/shared-library/lib-lib-dependency/b.h
+++ b/shared-library/lib-lib-dependency/b.h
@@ -1,6 +1,6 @@
#ifndef B_H
#define B_H
-void b(void);
+int b(void);
#endif
diff --git a/shared-library/lib-lib-dependency/main.c b/shared-library/lib-lib-dependency/main.c
index a13aaf4..9fdb940 100644
--- a/shared-library/lib-lib-dependency/main.c
+++ b/shared-library/lib-lib-dependency/main.c
@@ -1,9 +1,9 @@
-#include
+#include
#include
#include "a.h"
int main(void) {
- a();
+ assert(a() == 3);
return EXIT_SUCCESS;
}
diff --git a/shared-library/symbol-version/Makefile b/shared-library/symbol-version/Makefile
index 0074460..d0fc3dc 100644
--- a/shared-library/symbol-version/Makefile
+++ b/shared-library/symbol-version/Makefile
@@ -18,6 +18,9 @@ main1.out: main.c libcirosantilli_a.so
main2.out: main.c libcirosantilli_a.so
$(CC) -DV2 -L'.' main.c -o '$@' -lcirosantilli_a
+a.o: a.c
+ $(CC) -fPIC -c '$<' -o '$@'
+
libcirosantilli_a.so: a.o
$(CC) -Wl,--version-script,a.map -L'.' -shared a.o -o '$@'
diff --git a/shared-library/symbol-version/README.md b/shared-library/symbol-version/README.md
index cdc1017..a8167fe 100644
--- a/shared-library/symbol-version/README.md
+++ b/shared-library/symbol-version/README.md
@@ -4,4 +4,4 @@ Trying to replicate glibc's `symbol@@VERSION` madness.
This allows you to have a single library `v2`, that also contains symbols from `v1`.
- contains a nice example.
+
diff --git a/shared-library/symbol-version/a.c b/shared-library/symbol-version/a.c
index 147c8c2..51ff562 100644
--- a/shared-library/symbol-version/a.c
+++ b/shared-library/symbol-version/a.c
@@ -1,14 +1,12 @@
-#include
-
#include "a.h"
__asm__(".symver a1,a@LIBA_1");
-void a1(void) {
- puts("a1");
+int a1(void) {
+ return 1;
}
/* @@ means "default version". */
__asm__(".symver a2,a@@LIBA_2");
-void a2(void) {
- puts("a2");
+int a2(void) {
+ return 2;
}
diff --git a/shared-library/symbol-version/a.h b/shared-library/symbol-version/a.h
index 733fc06..d72f9ff 100644
--- a/shared-library/symbol-version/a.h
+++ b/shared-library/symbol-version/a.h
@@ -1,6 +1,6 @@
#ifndef A_H
#define A_H
-void a(void);
+int a(void);
#endif
diff --git a/shared-library/symbol-version/main.c b/shared-library/symbol-version/main.c
index 58048ed..26b0221 100644
--- a/shared-library/symbol-version/main.c
+++ b/shared-library/symbol-version/main.c
@@ -1,4 +1,4 @@
-#include
+#include
#include
#include "a.h"
@@ -12,6 +12,10 @@ __asm__(".symver a,a@LIBA_2");
#endif
int main(void) {
- a();
+#if defined(V1)
+ assert(a() == 1);
+#else
+ assert(a() == 2);
+#endif
return EXIT_SUCCESS;
}